code
stringlengths
12
2.05k
label
int64
0
1
programming_language
stringclasses
9 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
103
description
stringlengths
36
1.23k
url
stringlengths
36
48
label_name
stringclasses
2 values
public void translate(ServerAdvancementTabPacket packet, GeyserSession session) { AdvancementsCache advancementsCache = session.getAdvancementsCache(); advancementsCache.setCurrentAdvancementCategoryId(packet.getTabId()); advancementsCache.buildAndShowListForm(); }
0
Java
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
private void testEnc() throws Exception { KeyFactory kFact = KeyFactory.getInstance("DH", "BC"); Key k = kFact.generatePrivate(new PKCS8EncodedKeySpec(samplePrivEnc)); if (!Arrays.areEqual(samplePrivEnc, k.getEncoded())) { fail("private key re-encode failed"); } k = kFact.generatePublic(new X509EncodedKeySpec(samplePubEnc)); if (!Arrays.areEqual(samplePubEnc, k.getEncoded())) { fail("public key re-encode failed"); } k = kFact.generatePublic(new X509EncodedKeySpec(oldPubEnc)); if (!Arrays.areEqual(oldPubEnc, k.getEncoded())) { fail("old public key re-encode failed"); } k = kFact.generatePublic(new X509EncodedKeySpec(oldFullParams)); if (!Arrays.areEqual(oldFullParams, k.getEncoded())) { fail("old full public key re-encode failed"); } }
0
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
vulnerable
private void verifyHostname(X509Certificate cert) throws CertificateParsingException { try { Collection sans = cert.getSubjectAlternativeNames(); if (sans == null) { String dn = cert.getSubjectX500Principal().getName(); LdapName ln = new LdapName(dn); for (Rdn rdn : ln.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { String peer = client.getServerName().toLowerCase(); if (peer.equals(((String)rdn.getValue()).toLowerCase())) return; } } } else { Iterator i = sans.iterator(); while (i.hasNext()) { List nxt = (List)i.next(); if (((Integer)nxt.get(0)).intValue() == 2) { String peer = client.getServerName().toLowerCase(); if (peer.equals(((String)nxt.get(1)).toLowerCase())) return; } else if (((Integer)nxt.get(0)).intValue() == 7) { String peer = ((CConn)client).getSocket().getPeerAddress(); if (peer.equals(((String)nxt.get(1)).toLowerCase())) return; } } } Object[] answer = {"YES", "NO"}; int ret = JOptionPane.showOptionDialog(null, "Hostname ("+client.getServerName()+") does not match the"+ " server certificate, do you want to continue?", "Certificate hostname mismatch", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, answer, answer[0]); if (ret != JOptionPane.YES_OPTION) throw new WarningException("Certificate hostname mismatch."); } catch (CertificateParsingException e) { throw new SystemException(e.getMessage()); } catch (InvalidNameException e) { throw new SystemException(e.getMessage()); } }
1
Java
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
safe
protected String escape(String string) { String escaped = JavaEscape.escapeJava(string); // escape $ character since it has special meaning in groovy string escaped = escaped.replace("$", "\\$"); return escaped; }
0
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
private ObjectStreamClass verify(ObjectStreamClass streamClass) throws IOException, ClassNotFoundException { Class<?> aClass = resolveClass(streamClass); Package pkg = aClass.getPackage(); if (aClass.isPrimitive() // primitives are fine || aClass.isArray() // arrays are ok too || Throwable.class.isAssignableFrom(aClass)// exceptions are fine || CLASS_WHITELIST.contains(aClass) // whitelist JDK stuff we need || PKG_WHITELIST.contains(aClass.getPackage()) || pkg.getName().startsWith("org.elasticsearch")) { // es classes are ok return streamClass; } throw new NotSerializableException(aClass.getName()); }
1
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
safe
public void create_withNullThreadPool() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 100,10,10000); verify(jettyServerFactory, times(1)).create(100,10,10000); verifyNoMoreInteractions(jettyServerFactory); }
0
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
public static <T> T withPassword(AuthenticationRequestType type, Properties info, PasswordAction<char @Nullable [], T> action) throws PSQLException, IOException { char[] password = null; String authPluginClassName = PGProperty.AUTHENTICATION_PLUGIN_CLASS_NAME.get(info); if (authPluginClassName == null || authPluginClassName.equals("")) { // Default auth plugin simply pulls password directly from connection properties String passwordText = PGProperty.PASSWORD.get(info); if (passwordText != null) { password = passwordText.toCharArray(); } } else { AuthenticationPlugin authPlugin; try { authPlugin = (AuthenticationPlugin) ObjectFactory.instantiate(authPluginClassName, info, false, null); } catch (Exception ex) { LOGGER.log(Level.FINE, "Unable to load Authentication Plugin " + ex.toString()); throw new PSQLException(ex.getMessage(), PSQLState.UNEXPECTED_ERROR); } password = authPlugin.getPassword(type); } try { return action.apply(password); } finally { if (password != null) { java.util.Arrays.fill(password, (char) 0); } } }
0
Java
CWE-665
Improper Initialization
The software does not initialize or incorrectly initializes a resource, which might leave the resource in an unexpected state when it is accessed or used.
https://cwe.mitre.org/data/definitions/665.html
vulnerable
static String getVIMID() { if (vimIDConstructor != null) { Object vimID = null; try { vimID = vimIDConstructor.newInstance(); } catch (Exception i) { // might happen, fall through if it does } if (vimID != null) { return vimID.toString(); } } return "No VIM ID"; // TODO: maybe there is a system property we can use here. }
0
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
vulnerable
public static Object instantiate(String classname, Properties info, boolean tryString, @Nullable String stringarg) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { @Nullable Object[] args = {info}; Constructor<?> ctor = null; Class<?> cls = Class.forName(classname); try { ctor = cls.getConstructor(Properties.class); } catch (NoSuchMethodException ignored) { } if (tryString && ctor == null) { try { ctor = cls.getConstructor(String.class); args = new String[]{stringarg}; } catch (NoSuchMethodException ignored) { } } if (ctor == null) { ctor = cls.getConstructor(); args = new Object[0]; } return ctor.newInstance(args); }
0
Java
CWE-665
Improper Initialization
The software does not initialize or incorrectly initializes a resource, which might leave the resource in an unexpected state when it is accessed or used.
https://cwe.mitre.org/data/definitions/665.html
vulnerable
public AESCMAC() { super(new CMac(new AESFastEngine())); }
0
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
vulnerable
public void setUp(@TempDir Path tempDir) throws IOException { serverRepo = TempDirUtils.createTempDirectoryIn(tempDir, "testHgServerRepo").toFile(); clientRepo = TempDirUtils.createTempDirectoryIn(tempDir, "testHgClientRepo").toFile(); secondBranchWorkingCopy = TempDirUtils.createTempDirectoryIn(tempDir, "second").toFile(); setUpServerRepoFromHgBundle(serverRepo, new File("../common/src/test/resources/data/hgrepo.hgbundle")); workingDirectory = new File(clientRepo.getPath()); hgCommand = new HgCommand(null, workingDirectory, "default", serverRepo.getAbsolutePath(), null); hgCommand.clone(outputStreamConsumer, new UrlArgument(serverRepo.getAbsolutePath())); }
0
Java
CWE-77
Improper Neutralization of Special Elements used in a Command ('Command Injection')
The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/77.html
vulnerable
public void run() { for (;;) { ahead(100); back(100); } }
1
Java
CWE-862
Missing Authorization
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; }
1
Java
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
safe
public static boolean isPointOnCurve(final BigInteger x, final BigInteger y, final ECParameterSpec ecParameterSpec) { // Ensure the following condition is met: // (y^2) mod p = (x^3 + ax + b) mod p EllipticCurve curve = ecParameterSpec.getCurve(); BigInteger a = curve.getA(); BigInteger b = curve.getB(); BigInteger p = ((ECFieldFp) curve.getField()).getP(); BigInteger leftSide = (y.pow(2)).mod(p); BigInteger rightSide = (x.pow(3).add(a.multiply(x)).add(b)).mod(p); return leftSide.equals(rightSide); }
1
Java
CWE-347
Improper Verification of Cryptographic Signature
The software does not verify, or incorrectly verifies, the cryptographic signature for data.
https://cwe.mitre.org/data/definitions/347.html
safe
public void appendText(String text) { if (text == null) { return; } String previous = this.binding.textinput.getText().toString(); if (UIHelper.isLastLineQuote(previous)) { text = '\n' + text; } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) { text = " " + text; } this.binding.textinput.append(text); }
0
Java
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
private void testRandom( int size) throws Exception { AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DH", "BC"); a.init(size, new SecureRandom()); AlgorithmParameters params = a.generateParameters(); byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DH", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } DHParameterSpec dhP = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class); testGP("DH", size, 0, dhP.getG(), dhP.getP()); }
0
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
vulnerable
public int size() { try { return ByteUtils.safeBitLength(k.decode()); } catch (IntegerOverflowException e) { throw new ArithmeticException(e.getMessage()); } }
1
Java
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
public JpaOrder nullsFirst() { return with(NullHandling.NULLS_FIRST); }
1
Java
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
public void testInvalidUserIds() { testInvalidUserId("John<b>Doe</b>",true); testInvalidUserId("Jane'Doe'",true); testInvalidUserId("John&Doe",true); testInvalidUserId("Jane\"\"Doe",true); }
1
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
public void newDocumentWebHomeFromURLTemplateProviderSpecifiedButOldPageTypeButOverriddenFromUIToNonTerminal() throws Exception { // new document = xwiki:X.Y.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X", "Y"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(true); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider String templateProviderFullName = "XWiki.MyTemplateProvider"; when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName); when(mockRequest.getParameter("tocreate")).thenReturn("nonterminal"); // Mock 1 existing template provider mockExistingTemplateProviders(templateProviderFullName, new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, null, "page"); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: We are creating the document X.Y.WebHome as non-terminal, since even if the template provider did not // specify a "terminal" property and it used the old "page" type, the UI explicitly asked for a non-terminal // document. Also using a template, as specified in the template provider. verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context); }
0
Java
CWE-862
Missing Authorization
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
vulnerable
public void testHeaderNameEndsWithControlChar1d() { testHeaderNameEndsWithControlChar(0x1d); }
1
Java
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
boolean hasEncodedBytes() { return encoded != null; }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
public static JpaSort unsafe(Direction direction, String... properties) { Assert.notNull(direction, "Direction must not be null!"); Assert.notEmpty(properties, "Properties must not be empty!"); Assert.noNullElements(properties, "Properties must not contain null values!"); return unsafe(direction, Arrays.asList(properties)); }
1
Java
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
public void checkConnection(UrlArgument repositoryURL) { execute(createCommandLine("hg").withArgs("id", "--id").withArg(repositoryURL).withNonArgSecrets(secrets).withEncoding("utf-8"), new NamedProcessTag(repositoryURL.forDisplay())); }
0
Java
CWE-77
Improper Neutralization of Special Elements used in a Command ('Command Injection')
The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/77.html
vulnerable
public void existingDocumentFromUIDeprecated() throws Exception { // current document = xwiki:Main.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(false); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Submit from the UI space=X&page=Y when(mockRequest.getParameter("space")).thenReturn("X"); when(mockRequest.getParameter("page")).thenReturn("Y"); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: We are creating X.Y since the deprecated parameters were creating terminal documents by default. verify(mockURLFactory).createURL("X", "Y", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki", context); }
0
Java
CWE-862
Missing Authorization
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
vulnerable
public void highlightInMuc(Conversation conversation, String nick) { switchToConversation(conversation, null, false, nick, false, false); }
1
Java
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
safe
public PBEWithSHA256AESCBC128() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 128, 16); }
1
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
safe
private void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) { final Point2D corner = getPosition(elkNode); final URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight()); PackageStyle packageStyle = group.getPackageStyle(); final ISkinParam skinParam = diagram.getSkinParam(); if (packageStyle == null) packageStyle = skinParam.packageStyle(); final UmlDiagramType umlDiagramType = diagram.getUmlDiagramType(); final Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol()) .getMergedStyle(skinParam.getCurrentStyleBuilder()); final double shadowing = style.value(PName.Shadowing).asDouble(); final UStroke stroke = Cluster.getStrokeInternal(group, skinParam, style); HColor backColor = getBackColor(umlDiagramType); backColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(), umlDiagramType.getStyleName(), group.getUSymbol()); final double roundCorner = group.getUSymbol() == null ? 0 : group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype()); final TextBlock ztitle = getTitleBlock(group); final TextBlock zstereo = TextBlockUtils.empty(0, 0); final ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle, zstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke); final HColor borderColor = HColorUtils.BLACK; decoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner, skinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null), skinParam.getStereotypeAlignment(), 0); // // Print a simple rectangle right now // ug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect); }
0
Java
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
public Poly1305() { super(new org.bouncycastle.crypto.macs.Poly1305(new AESFastEngine())); }
0
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
vulnerable
static public AsymmetricKeyParameter generatePublicKeyParameter( PublicKey key) throws InvalidKeyException { if (key instanceof BCDHPublicKey) { return ((BCDHPublicKey)key).engineGetKeyParameters(); } if (key instanceof DHPublicKey) { DHPublicKey k = (DHPublicKey)key; return new DHPublicKeyParameters(k.getY(), new DHParameters(k.getParams().getP(), k.getParams().getG(), null, k.getParams().getL())); } throw new InvalidKeyException("can't identify DH public key."); }
1
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
safe
public void testMatchType() { JWKMatcher matcher = new JWKMatcher.Builder().keyType(KeyType.RSA).build(); assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").build())); assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build())); assertEquals("kty=RSA", matcher.toString()); }
0
Java
CWE-347
Improper Verification of Cryptographic Signature
The software does not verify, or incorrectly verifies, the cryptographic signature for data.
https://cwe.mitre.org/data/definitions/347.html
vulnerable
public void testHeaderNameStartsWithControlChar1f() { testHeaderNameStartsWithControlChar(0x1f); }
1
Java
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (plaintextOffset > plaintext.length) space = 0; else space = plaintext.length - plaintextOffset; if (!haskey) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); setup(ad); ghash.update(ciphertext, ciphertextOffset, dataLen); ghash.pad(ad != null ? ad.length : 0, dataLen); ghash.finish(enciv, 0, 16); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; }
0
Java
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { Class<?> primitiveType = PRIMITIVE_TYPES.get(desc.getName()); if (primitiveType != null) { return primitiveType; } if (!isClassValid(desc.getName())) { throw new InvalidClassException("Unauthorized deserialization attempt", desc.getName()); } return super.resolveClass(desc); }
1
Java
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
safe
private void testTwoParty(String algName, int size, int privateValueSize, KeyPairGenerator keyGen) throws Exception { testTwoParty(algName, size, privateValueSize, keyGen.generateKeyPair(), keyGen.generateKeyPair()); }
1
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
safe
public static Document parseText(String text) throws DocumentException { SAXReader reader = SAXReader.createDefault(); String encoding = getEncoding(text); InputSource source = new InputSource(new StringReader(text)); source.setEncoding(encoding); Document result = reader.read(source); // if the XML parser doesn't provide a way to retrieve the encoding, // specify it manually if (result.getXMLEncoding() == null) { result.setXMLEncoding(encoding); } return result; }
1
Java
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
safe
public void translate(ServerCloseWindowPacket packet, GeyserSession session) { // Sometimes the server can request a window close of ID 0... when the window isn't even open // Don't confirm in this instance InventoryUtils.closeInventory(session, packet.getWindowId(), (session.getOpenInventory() != null && session.getOpenInventory().getId() == packet.getWindowId())); }
0
Java
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
public static void testLongSetCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding2); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MySetStruct(), iprot); }
1
Java
CWE-770
Allocation of Resources Without Limits or Throttling
The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
public static byte[] transcodeSignatureToConcat(final byte[] derSignature, int outputLength) throws JOSEException { if (derSignature.length < 8 || derSignature[0] != 48) { throw new JOSEException("Invalid ECDSA signature format"); } int offset; if (derSignature[1] > 0) { offset = 2; } else if (derSignature[1] == (byte) 0x81) { offset = 3; } else { throw new JOSEException("Invalid ECDSA signature format"); } byte rLength = derSignature[offset + 1]; int i; for (i = rLength; (i > 0) && (derSignature[(offset + 2 + rLength) - i] == 0); i--) { // do nothing } byte sLength = derSignature[offset + 2 + rLength + 1]; int j; for (j = sLength; (j > 0) && (derSignature[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--) { // do nothing } int rawLen = Math.max(i, j); rawLen = Math.max(rawLen, outputLength / 2); if ((derSignature[offset - 1] & 0xff) != derSignature.length - offset || (derSignature[offset - 1] & 0xff) != 2 + rLength + 2 + sLength || derSignature[offset] != 2 || derSignature[offset + 2 + rLength] != 2) { throw new JOSEException("Invalid ECDSA signature format"); } final byte[] concatSignature = new byte[2 * rawLen]; System.arraycopy(derSignature, (offset + 2 + rLength) - i, concatSignature, rawLen - i, i); System.arraycopy(derSignature, (offset + 2 + rLength + 2 + sLength) - j, concatSignature, 2 * rawLen - j, j); return concatSignature; }
0
Java
CWE-347
Improper Verification of Cryptographic Signature
The software does not verify, or incorrectly verifies, the cryptographic signature for data.
https://cwe.mitre.org/data/definitions/347.html
vulnerable
private static void writeBaloFile(HttpURLConnection conn, Path baloPath, String fullModuleName, long resContentLength) { try (InputStream inputStream = conn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(baloPath.toString())) { writeAndHandleProgress(inputStream, outputStream, resContentLength / 1024, fullModuleName); } catch (IOException e) { createError("error occurred copying the balo file: " + e.getMessage()); } }
0
Java
CWE-306
Missing Authentication for Critical Function
The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
void getGadgets() throws Exception { assertEquals(new ArrayList<>(), this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext)); BaseObject gadgetObject1 = mock(BaseObject.class); when(xWikiDocument.getXObjects(gadgetClassReference)).thenReturn(Collections.singletonList(gadgetObject1)); when(gadgetObject1.getOwnerDocument()).thenReturn(ownerDocument); when(gadgetObject1.getStringValue("title")).thenReturn("Gadget 1"); when(gadgetObject1.getLargeStringValue("content")).thenReturn("Some content"); when(gadgetObject1.getStringValue("position")).thenReturn("0"); when(gadgetObject1.getNumber()).thenReturn(42); List<Gadget> gadgets = this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext); assertEquals(1, gadgets.size()); Gadget gadget = gadgets.get(0); assertEquals("Gadget 1", gadget.getTitle().get(0).toString()); assertEquals("Some content", gadget.getContent().get(0).toString()); assertEquals("42", gadget.getId()); }
0
Java
CWE-94
Improper Control of Generation of Code ('Code Injection')
The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
public void fatalError(SAXParseException e) { }
0
Java
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
vulnerable
List<Modification> findRecentModifications(int count) { // Currently impossible to check modifications on a remote repository. InMemoryStreamConsumer consumer = inMemoryConsumer(); bombUnless(pull(consumer), "Failed to run hg pull command: " + consumer.getAllOutput()); CommandLine hg = hg("log", "--limit", String.valueOf(count), "-b", branch, "--style", templatePath()); return new HgModificationSplitter(execute(hg)).modifications(); }
0
Java
CWE-77
Improper Neutralization of Special Elements used in a Command ('Command Injection')
The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/77.html
vulnerable
final void add(CharSequence name, Iterable<String> values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); final int h = normalizedName.hashCode(); final int i = index(h); for (String v : values) { requireNonNullElement(values, v); add0(h, i, normalizedName, v); } }
0
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (plaintextOffset > plaintext.length) space = 0; else space = plaintext.length - plaintextOffset; if (!haskey) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); setup(ad); poly.update(ciphertext, ciphertextOffset, dataLen); finish(ad, dataLen); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; }
0
Java
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
public void doesNotPrefixAliasedFunctionCallNameWithMultipleStringParameters() { String query = "SELECT CONCAT(m.name, 'foo') AS extendedName FROM Magazine m"; Sort sort = new Sort("extendedName"); assertThat(applySorting(query, sort, "m"), endsWith("order by extendedName asc")); }
1
Java
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
public void validateFail2(ViolationCollector col) { col.addViolation("p2", FAILED); }
1
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
safe
public void translate(ServerClearTitlesPacket packet, GeyserSession session) { SetTitlePacket titlePacket = new SetTitlePacket(); // TODO handle packet.isResetTimes() titlePacket.setType(SetTitlePacket.Type.CLEAR); titlePacket.setText(""); titlePacket.setXuid(""); titlePacket.setPlatformOnlineId(""); session.sendUpstreamPacket(titlePacket); }
0
Java
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
public List<String> getShellCommandLine( String[] arguments ) { List<String> commandLine = new ArrayList<String>(); if ( getShellCommand() != null ) { commandLine.add( getShellCommand() ); } if ( getShellArgs() != null ) { commandLine.addAll( getShellArgsList() ); } commandLine.addAll( getCommandLine( getExecutable(), arguments ) ); return commandLine; }
0
Java
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
public static String validateIconSize(String iconSize) throws SecurityException { if (!ICON_SIZE.matcher(iconSize).matches()) { throw new SecurityException("invalid iconSize"); } return iconSize; }
1
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (plaintextOffset > plaintext.length) space = 0; else space = plaintext.length - plaintextOffset; if (!haskey) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); setup(ad); poly.update(ciphertext, ciphertextOffset, dataLen); finish(ad, dataLen); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; }
0
Java
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
public static String decodePathParam(String pathParam) { if (pathParam.indexOf('%') < 0) { // No need to decode because it's not percent-encoded return pathParam; } // Decode percent-encoded characters. return slowDecodePath(pathParam, true); }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
public void testSquare_OpenSSLBug() { int COUNT = 100; for (int i = 0; i < COUNT; ++i) { ECFieldElement x = generateSquareInput_OpenSSLBug(); BigInteger X = x.toBigInteger(); BigInteger R = X.multiply(X).mod(Q); ECFieldElement z = x.square(); BigInteger Z = z.toBigInteger(); assertEquals(R, Z); } }
1
Java
CWE-19
Data Processing Errors
Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information.
https://cwe.mitre.org/data/definitions/19.html
safe
public void encryptedValueStaysTheSameAfterRoundtrip() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty(new PasswordParameterDefinition("p", "s3cr37", "Keep this a secret"))); project = j.configRoundtrip(project); String round1 = project.getConfigFile().asString(); project = j.configRoundtrip(project); String round2 = project.getConfigFile().asString(); assertEquals(round1, round2); //But reconfiguring will make it a new value project = j.jenkins.getItemByFullName(project.getFullName(), FreeStyleProject.class); project.removeProperty(ParametersDefinitionProperty.class); project.addProperty(new ParametersDefinitionProperty(new PasswordParameterDefinition("p", "s3cr37", "Keep this a secret"))); project = j.configRoundtrip(project); String round3 = project.getConfigFile().asString(); assertNotEquals(round2, round3); //Saving again will produce the same project = j.configRoundtrip(project); String round4 = project.getConfigFile().asString(); assertEquals(round3, round4); }
1
Java
CWE-326
Inadequate Encryption Strength
The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.
https://cwe.mitre.org/data/definitions/326.html
safe
public void emptyHeaderNameNotAllowed() { newEmptyHeaders().add("", "foo"); }
0
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
public void testSetContentFromFile() throws Exception { TestHttpData test = new TestHttpData("test", UTF_8, 0); try { File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); tmpFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmpFile); byte[] bytes = new byte[4096]; PlatformDependent.threadLocalRandom().nextBytes(bytes); try { fos.write(bytes); fos.flush(); } finally { fos.close(); } test.setContent(tmpFile); ByteBuf buf = test.getByteBuf(); assertEquals(buf.readerIndex(), 0); assertEquals(buf.writerIndex(), bytes.length); assertArrayEquals(bytes, test.get()); assertArrayEquals(bytes, ByteBufUtil.getBytes(buf)); } finally { //release the ByteBuf test.delete(); } }
0
Java
CWE-378
Creation of Temporary File With Insecure Permissions
Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.
https://cwe.mitre.org/data/definitions/378.html
vulnerable
public void testWrapMemoryMapped() throws Exception { File file = File.createTempFile("netty-test", "tmp"); FileChannel output = null; FileChannel input = null; ByteBuf b1 = null; ByteBuf b2 = null; try { output = new RandomAccessFile(file, "rw").getChannel(); byte[] bytes = new byte[1024]; PlatformDependent.threadLocalRandom().nextBytes(bytes); output.write(ByteBuffer.wrap(bytes)); input = new RandomAccessFile(file, "r").getChannel(); ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size()); b1 = buffer(m); ByteBuffer dup = m.duplicate(); dup.position(2); dup.limit(4); b2 = buffer(dup); Assert.assertEquals(b2, b1.slice(2, 2)); } finally { if (b1 != null) { b1.release(); } if (b2 != null) { b2.release(); } if (output != null) { output.close(); } if (input != null) { input.close(); } file.delete(); } }
0
Java
CWE-378
Creation of Temporary File With Insecure Permissions
Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.
https://cwe.mitre.org/data/definitions/378.html
vulnerable
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (!found) { if (!desc.getName().equals(mainClass.getName())) { throw new InvalidClassException( "unexpected class: ", desc.getName()); } else { found = true; } } else { if (!components.contains(desc.getName())) { throw new InvalidClassException( "unexpected class: ", desc.getName()); } } return super.resolveClass(desc); }
1
Java
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
safe
public void testInvalidGroupIds() { testInvalidGroupId("John<b>Doe</b>",true); testInvalidGroupId("Jane'Doe'",true); testInvalidGroupId("John&Doe",true); testInvalidGroupId("Jane\"\"Doe",true); }
1
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
public boolean isAvailable() { try { GeoTools.getInitialContext(); return true; } catch (Exception e) { return false; } }
0
Java
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
public byte[] toByteArray() { /* index || secretKeySeed || secretKeyPRF || publicSeed || root */ int n = params.getDigestSize(); int indexSize = (params.getHeight() + 7) / 8; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize; byte[] out = new byte[totalSize]; int position = 0; /* copy index */ byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize); XMSSUtil.copyBytesAtOffset(out, indexBytes, position); position += indexSize; /* copy secretKeySeed */ XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position); position += secretKeySize; /* copy secretKeyPRF */ XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position); position += secretKeyPRFSize; /* copy publicSeed */ XMSSUtil.copyBytesAtOffset(out, publicSeed, position); position += publicSeedSize; /* copy root */ XMSSUtil.copyBytesAtOffset(out, root, position); /* concatenate bdsState */ try { return Arrays.concatenate(out, XMSSUtil.serialize(bdsState)); } catch (IOException e) { throw new IllegalStateException("error serializing bds state: " + e.getMessage(), e); } }
1
Java
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
safe
public void testIntegerOverflowHmacBypass() throws Exception { SecretKey inputKey = new SecretKeySpec(INPUT_KEY_256, "AES"); Assert.assertArrayEquals("Input key", INPUT_KEY_256, inputKey.getEncoded()); byte[] iv = new byte[16]; byte[] aad = new byte[8]; byte[] plaintext = new byte[536870928]; for (int i = 0; i < plaintext.length; i++ ){ // Doesn't matter what value is, but rand is too expensive for large array plaintext[i] = (byte) i; } AuthenticatedCipherText act; try { act = AESCBC.encryptAuthenticated(inputKey, iv, plaintext, aad, null, null); } catch (OutOfMemoryError e) { System.out.println("Test not run due to " + e); return; } byte[] ciphertext = act.getCipherText(); byte[] authTag = act.getAuthenticationTag(); // Now shift aad and ciphertext around so that HMAC doesn't change, // but the plaintext will change. int n = 0; byte[] buffer = new byte[aad.length + iv.length + ciphertext.length]; System.arraycopy(aad, 0, buffer, n, aad.length); n += aad.length; System.arraycopy(iv, 0, buffer, n, iv.length); n += iv.length; System.arraycopy(ciphertext, 0, buffer, n, ciphertext.length); // Note that due to integer overflow :536870920 * 8 = 64 int newAadSize = 536870920; byte[] newAad = Arrays.copyOfRange(buffer, 0, newAadSize); byte[] newIv = Arrays.copyOfRange(buffer, newAadSize, newAadSize + 16); byte[] newCiphertext = Arrays.copyOfRange(buffer, newAadSize + 16, buffer.length); try { byte[] decrypted = AESCBC.decryptAuthenticated(inputKey, newIv, newCiphertext, newAad, authTag, // Note that the authTag does NOT change. null, null); // Reaching this point means that the HMac check is // bypassed although the decrypted data is different // from plaintext. // Assert.assertArrayEquals(decrypted, plaintext); fail(); } catch (JOSEException ignored) { // ok } }
1
Java
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
final void addObject(CharSequence name, Object... values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); for (Object v : values) { requireNonNullElement(values, v); addObject(normalizedName, v); } }
0
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
public static Document toXml(final List<IBaseDataObject> list) { final Element root = new Element("payload-list"); for (final IBaseDataObject d : list) { final Document doc = toXml(d); root.addContent(doc.detachRootElement()); logger.debug("Adding xml content for " + d.shortName() + " to document"); } final Document doc = new Document(root); return doc; }
0
Java
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); return is.readObject(); }
0
Java
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
void percent() { final PathAndQuery res = parse("/%25"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/%25"); assertThat(res.query()).isNull(); }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
public boolean deleteSynchronously(String mediaPackageId) throws SearchException, UnauthorizedException, NotFoundException { SearchResult result; try { result = solrRequester.getForWrite(new SearchQuery().withId(mediaPackageId)); if (result.getItems().length == 0) { logger.warn( "Can not delete mediapackage {}, which is not available for the current user to delete from the search index.", mediaPackageId); return false; } logger.info("Removing mediapackage {} from search index", mediaPackageId); Date now = new Date(); try { persistence.deleteMediaPackage(mediaPackageId, now); logger.info("Removed mediapackage {} from search persistence", mediaPackageId); } catch (NotFoundException e) { // even if mp not found in persistence, it might still exist in search index. logger.info("Could not find mediapackage with id {} in persistence, but will try remove it from index, anyway.", mediaPackageId); } catch (SearchServiceDatabaseException e) { logger.error("Could not delete media package with id {} from persistence storage", mediaPackageId); throw new SearchException(e); } return indexManager.delete(mediaPackageId, now); } catch (SolrServerException e) { logger.info("Could not delete media package with id {} from search index", mediaPackageId); throw new SearchException(e); } }
0
Java
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
vulnerable
private static String slowDecodePath(String path, boolean decodeSlash) { // An invalid character is replaced with 0xFF, which will be replaced into '�' by UTF-8 decoder. final int len = path.length(); try (TemporaryThreadLocals tempThreadLocals = TemporaryThreadLocals.acquire()) { final byte[] buf = tempThreadLocals.byteArray(len); int dstLen = 0; for (int i = 0; i < len; i++) { final char ch = path.charAt(i); if (ch != '%') { buf[dstLen++] = (byte) ((ch & 0xFF80) == 0 ? ch : 0xFF); continue; } // Decode a percent-encoded character. final int hexEnd = i + 3; if (hexEnd > len) { // '%' or '%x' (must be followed by two hexadigits) buf[dstLen++] = (byte) 0xFF; break; } final int digit1 = decodeHexNibble(path.charAt(++i)); final int digit2 = decodeHexNibble(path.charAt(++i)); if (digit1 < 0 || digit2 < 0) { // The first or second digit is not hexadecimal. buf[dstLen++] = (byte) 0xFF; } else { final byte decoded = (byte) ((digit1 << 4) | digit2); if (decodeSlash || decoded != 0x2F) { buf[dstLen++] = decoded; } else { buf[dstLen++] = '%'; buf[dstLen++] = '2'; buf[dstLen++] = (byte) path.charAt(i); // f or F - preserve the case. } } } return new String(buf, 0, dstLen, StandardCharsets.UTF_8); } }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
public void testCBCPaddingOracleAttackOldConcatKDF() throws Exception { SecretKey inputKey = new SecretKeySpec(INPUT_KEY_256, "AES"); Assert.assertArrayEquals("Input key", INPUT_KEY_256, inputKey.getEncoded()); AuthenticatedCipherText act = AESCBC.encryptWithConcatKDF( new JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A128CBC_HS256_DEPRECATED), new SecretKeySpec(INPUT_KEY_256, "AES"), Base64URL.encode(INPUT_KEY_256), // mock IV, PLAIN_TEXT, null, null ); byte[] cipherText = act.getCipherText(); // Now change the cipher text to make CBC padding invalid. cipherText[cipherText.length - 1] ^= 0x01; try { AESCBC.decryptWithConcatKDF( new JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A128CBC_HS256_DEPRECATED), new SecretKeySpec(INPUT_KEY_256, "AES"), Base64URL.encode(INPUT_KEY_256), // mock Base64URL.encode(IV), Base64URL.encode(cipherText), Base64URL.encode(act.getAuthenticationTag()), null, null ); } catch (JOSEException e) { assertEquals("MAC check failed", e.getMessage()); } }
1
Java
CWE-354
Improper Validation of Integrity Check Value
The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
https://cwe.mitre.org/data/definitions/354.html
safe
public void withCallback() throws IOException, ServletException { prepareStandardInitialisation(); ByteArrayOutputStream sw = initRequestResponseMocks( "myCallback", getStandardRequestSetup(), new Runnable() { public void run() { response.setCharacterEncoding("utf-8"); response.setContentType("text/javascript"); response.setStatus(200); } }); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getAttribute("subject")).andReturn(null); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null); replay(request, response); servlet.doGet(request, response); assertTrue(sw.toString().matches("^myCallback\\(.*\\);$")); servlet.destroy(); }
1
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
public static DomainSocketAddress newSocketAddress() { try { File file; do { file = File.createTempFile("NETTY", "UDS"); if (!file.delete()) { throw new IOException("failed to delete: " + file); } } while (file.getAbsolutePath().length() > 128); return new DomainSocketAddress(file); } catch (IOException e) { throw new IllegalStateException(e); } }
0
Java
CWE-379
Creation of Temporary File in Directory with Insecure Permissions
The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file.
https://cwe.mitre.org/data/definitions/379.html
vulnerable
public void corsAccessCheck() { BackendManager backendManager = new BackendManager(config,log); assertTrue(backendManager.isCorsAccessAllowed("http://bla.com")); backendManager.destroy(); }
0
Java
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
vulnerable
public MultiMap set(String name, String value) { HttpUtils.validateHeader(name, value); headers.set(toLowerCase(name), value); return this; }
1
Java
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
public static synchronized InitialContext getInitialContext(final Hints hints) throws NamingException { return getInitialContext(); }
0
Java
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { UserFactory.init(); } catch (Throwable e) { throw new ServletException("AddNewUserServlet: Error initialising user factory." + e); } UserManager userFactory = UserFactory.getInstance(); String userID = request.getParameter("userID"); if (userID != null && userID.matches(".*[&<>\"`']+.*")) { throw new ServletException("User ID must not contain any HTML markup."); } String password = request.getParameter("pass1"); boolean hasUser = false; try { hasUser = userFactory.hasUser(userID); } catch (Throwable e) { throw new ServletException("can't determine if user " + userID + " already exists in users.xml.", e); } if (hasUser) { RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/userGroupView/users/newUser.jsp?action=redo"); dispatcher.forward(request, response); } else { final Password pass = new Password(); pass.setEncryptedPassword(UserFactory.getInstance().encryptedPassword(password, true)); pass.setSalt(true); final User newUser = new User(); newUser.setUserId(userID); newUser.setPassword(pass); final HttpSession userSession = request.getSession(false); userSession.setAttribute("user.modifyUser.jsp", newUser); // forward the request for proper display RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/userGroupView/users/modifyUser.jsp"); dispatcher.forward(request, response); } }
1
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
public void doesNotPrefixAliasedFunctionCallNameWithUnderscores() { String query = "SELECT AVG(m.price) AS avg_price FROM Magazine m"; Sort sort = new Sort("avg_price"); assertThat(applySorting(query, sort, "m"), endsWith("order by avg_price asc")); }
1
Java
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
public String getShortDescription() { if(note != null) { return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, note); } else { return Messages.Cause_RemoteCause_ShortDescription(addr); } }
0
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
public void process(InputStream in, ZipEntry zipEntry) throws IOException { String root = getRootName(zipEntry.getName()); if (rootDir == null) { rootDir = root; } else if (!rootDir.equals(root)) { throw new ZipException("Unwrapping with multiple roots is not supported, roots: " + rootDir + ", " + root); } String name = mapper.map(getUnrootedName(root, zipEntry.getName())); if (name != null) { File file = new File(outputDir, name); /* If we see the relative traversal string of ".." we need to make sure * that the outputdir + name doesn't leave the outputdir. See * DirectoryTraversalMaliciousTest for details. */ if (name.indexOf("..") != -1 && !file.getCanonicalPath().startsWith(outputDir.getCanonicalPath())) { throw new ZipException("The file "+name+" is trying to leave the target output directory of "+outputDir+". Ignoring this file."); } if (zipEntry.isDirectory()) { FileUtils.forceMkdir(file); } else { FileUtils.forceMkdir(file.getParentFile()); if (log.isDebugEnabled() && file.exists()) { log.debug("Overwriting file '{}'.", zipEntry.getName()); } FileUtils.copy(in, file); } } }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
private void markCookieAsHttpOnly(ServletContext context) { try { Method m; try { m = context.getClass().getMethod("getSessionCookieConfig"); } catch (NoSuchMethodException x) { // 3.0+ LOGGER.log(Level.FINE, "Failed to set secure cookie flag", x); return; } Object sessionCookieConfig = m.invoke(context); // not exposing session cookie to JavaScript to mitigate damage caused by XSS Class scc = Class.forName("javax.servlet.SessionCookieConfig"); Method setHttpOnly = scc.getMethod("setHttpOnly",boolean.class); setHttpOnly.invoke(sessionCookieConfig,true); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to set HTTP-only cookie flag", e); } }
1
Java
CWE-254
7PK - Security Features
Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management.
https://cwe.mitre.org/data/definitions/254.html
safe
public boolean isIncludeInternalDTDDeclarations() { return includeInternalDTDDeclarations; }
0
Java
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
vulnerable
public String resolveSqlDriverNameFromJar(String driverFileUrl) { String tempFilePath = "temp/" + UUID.randomUUID() + ".jar"; File driverFile = doDownload(driverFileUrl, tempFilePath); String className = doResolveSqlDriverNameFromJar(driverFile); try { Files.deleteIfExists(driverFile.toPath()); } catch (IOException e) { log.error("delete driver error " + tempFilePath, e); } return className; }
0
Java
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
private static boolean isSlash(byte b) { switch (b) { case '/': case '\\': return true; default: return false; } }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
public void tearDown() throws Exception { if(embeddedServer != null) embeddedServer.extinguish(); }
0
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
public void addElementPrefix() { Element root = DocumentHelper.createElement("root"); root.addElement("ns>:element", "http://example.com/namespace"); }
1
Java
CWE-91
XML Injection (aka Blind XPath Injection)
The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system.
https://cwe.mitre.org/data/definitions/91.html
safe
protected int getExpectedErrors() { return hasJavaNetURLPermission ? 2 : 1; // Security error must be reported as an error. Java 8 reports two errors. }
0
Java
CWE-862
Missing Authorization
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
vulnerable
public BCXMSSPrivateKey(PrivateKeyInfo keyInfo) throws IOException { XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters()); this.treeDigest = keyParams.getTreeDigest().getAlgorithm(); XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey()); try { XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest))) .withIndex(xmssPrivateKey.getIndex()) .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed()) .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF()) .withPublicSeed(xmssPrivateKey.getPublicSeed()) .withRoot(xmssPrivateKey.getRoot()); if (xmssPrivateKey.getBdsState() != null) { keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState())); } this.keyParams = keyBuilder.build(); } catch (ClassNotFoundException e) { throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage()); } }
0
Java
CWE-470
Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')
The application uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code.
https://cwe.mitre.org/data/definitions/470.html
vulnerable
public static final void toStream(Binder binder, ZipOutputStream zout) throws IOException { try(OutputStream out=new ShieldOutputStream(zout)) { myStream.toXML(binder, out); } catch (Exception e) { log.error("Cannot export this map: " + binder, e); } }
0
Java
CWE-91
XML Injection (aka Blind XPath Injection)
The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system.
https://cwe.mitre.org/data/definitions/91.html
vulnerable
public void testExcludes() { final Collection<String> patterns = new ArrayList<String>() {{ add( "git://**" ); add( "**/repo/**" ); }}; { final Path path = Paths.get( URI.create( "file:///Users/home" ) ); Assert.assertFalse( excludes( patterns, path ) ); } { final Path path = Paths.get( URI.create( "git://antpathmatcher" ) ); Assert.assertTrue( excludes( patterns, path ) ); } { final Path path = Paths.get( URI.create( "git://master@antpathmatcher" ) ); Assert.assertTrue( excludes( patterns, path ) ); } }
1
Java
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
safe
public GCM() { super(new GCMBlockCipher(new AESEngine())); }
1
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
safe
private static Stream<Arguments> provideFilesAndExpectedExceptionType() { return Stream.of( Arguments.of("abnormal/corrupt-header.rar", CorruptHeaderException.class), Arguments.of("abnormal/mainHeaderNull.rar", BadRarArchiveException.class) ); }
0
Java
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
vulnerable
void noEncoding() { final PathAndQuery res = parse("/a?b=c"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/a"); assertThat(res.query()).isEqualTo("b=c"); }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
public void testSetNullHeaderValue() { final HttpHeadersBase headers = newEmptyHeaders(); headers.set("test", (String) null); }
0
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
public void testInvalidUserId(final String userId, final boolean mustFail) { adminPage(); findElementByLink("Configure Users, Groups and On-Call Roles").click(); findElementByLink("Configure Users").click(); findElementByLink("Add new user").click(); enterText(By.id("userID"), userId); enterText(By.id("pass1"), "SmokeTestPassword"); enterText(By.id("pass2"), "SmokeTestPassword"); findElementByXpath("//button[@type='submit' and text()='OK']").click(); if (mustFail) { try { final Alert alert = wait.withTimeout(Duration.of(5, ChronoUnit.SECONDS)).until(ExpectedConditions.alertIsPresent()); alert.dismiss(); } catch (final Exception e) { LOG.debug("Got an exception waiting for a 'invalid user ID' alert.", e); throw e; } } else { wait.until(ExpectedConditions.elementToBeClickable(By.name("finish"))); } }
1
Java
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
safe
public void testXXEProcessVulnerability() throws Exception { Resource processResource = ResourceFactory.newClassPathResource("xxe-protection/BPMN2-XXE-Process.bpmn2"); File dtdFile = new File("src/test/resources/xxe-protection/external.dtd"); assertTrue(dtdFile.exists()); String dtdContent = IoUtils.readFileAsString(dtdFile); dtdContent = dtdContent.replaceAll("@@PATH@@", dtdFile.getParentFile().getAbsolutePath()); IoUtils.write(dtdFile, dtdContent.getBytes("UTF-8")); byte[] data = IoUtils.readBytesFromInputStream(processResource.getInputStream()); String processAsString = new String(data, "UTF-8"); // replace place holders with actual paths File testFiles = new File("src/test/resources/xxe-protection"); assertTrue(testFiles.exists()); String path = testFiles.getAbsolutePath(); processAsString = processAsString.replaceAll("@@PATH@@", path); Resource resource = ResourceFactory.newReaderResource(new StringReader(processAsString)); resource.setSourcePath(processResource.getSourcePath()); resource.setTargetPath(processResource.getTargetPath()); KieBase kbase = createKnowledgeBaseFromResources(resource); KieSession ksession = createKnowledgeSession(kbase); ProcessInstance processInstance = ksession.startProcess("async-examples.bp1"); String var1 = getProcessVarValue(processInstance, "testScript1"); String var2 = getProcessVarValue(processInstance, "testScript2"); assertNull(var1); assertNull(var2); assertTrue(processInstance.getState() == ProcessInstance.STATE_COMPLETED); }
1
Java
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
safe
public Map<String, FileEntry> generatorCode(TableDetails tableDetails, String tablePrefix, Map<String, String> customProperties, List<TemplateFile> templateFiles) { Map<String, FileEntry> map = new HashMap<>(templateFiles.size()); // 模板渲染 Map<String, Object> context = GenUtils.getContext(tableDetails, tablePrefix, customProperties); for (TemplateFile templateFile : templateFiles) { FileEntry fileEntry = new FileEntry(); fileEntry.setType(templateFile.getType()); // 替换路径中的占位符 String filename = StrUtil.format(templateFile.getFilename(), context); fileEntry.setFilename(filename); String parentFilePath = GenUtils.evaluateRealPath(templateFile.getParentFilePath(), context); fileEntry.setParentFilePath(parentFilePath); // 如果是文件 if (TemplateEntryTypeEnum.FILE.getType().equals(fileEntry.getType())) { fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, filename)); // 文件内容渲染 TemplateEngineTypeEnum engineTypeEnum = TemplateEngineTypeEnum.of(templateFile.getEngineType()); String content = templateEngineDelegator.render(engineTypeEnum, templateFile.getContent(), context); fileEntry.setContent(content); } else { String currentPath = GenUtils.evaluateRealPath(templateFile.getFilename(), context); fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, currentPath)); } map.put(fileEntry.getFilePath(), fileEntry); } return map; }
0
Java
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
public void ecpFlowCreatesTransientSessions() { // Disable ECP_FLOW_ENABLED switch getCleanup().addCleanup(ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_ECP_SP) .setAttribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "false") .setAttribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false") .update()); // Successfully login using ECP flow SAML2Object samlObject = new SamlClientBuilder() .authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_ECP_SP, SAML_ASSERTION_CONSUMER_URL_ECP_SP, SOAP) .basicAuthentication(bburkeUser) .build() .executeAndTransform(SOAP::extractResponse).getSamlObject(); assertThat(samlObject, isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS)); ResponseType loginResp1 = (ResponseType) samlObject; AuthnStatementType sessionId = (AuthnStatementType) loginResp1.getAssertions().get(0).getAssertion().getStatements().iterator().next(); String userSessionId = sessionId.getSessionIndex().split("::")[0]; // Test that the user session with the given ID does not exist testingClient.server().run(session -> { RealmModel realmByName = session.realms().getRealmByName(REALM_NAME); UserSessionModel userSession = session.sessions().getUserSession(realmByName, userSessionId); assertThat(userSession, nullValue()); }); }
1
Java
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
safe
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userID = request.getParameter("userID"); String newID = request.getParameter("newID"); if (newID != null && newID.matches(".*[&<>\"`']+.*")) { throw new ServletException("User ID must not contain any HTML markup."); } // now save to the xml file try { UserManager userFactory = UserFactory.getInstance(); userFactory.renameUser(userID, newID); } catch (Throwable e) { throw new ServletException("Error renaming user " + userID + " to " + newID, e); } response.sendRedirect("list.jsp"); }
1
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
final void add(CharSequence name, Iterable<String> values) { final AsciiString normalizedName = HttpHeaderNames.of(name); requireNonNull(values, "values"); final int h = normalizedName.hashCode(); final int i = index(h); for (String v : values) { requireNonNullElement(values, v); add0(h, i, normalizedName, v); } }
1
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
safe
public void testAADLengthComputation() { Assert.assertArrayEquals(AAD_LENGTH, com.nimbusds.jose.crypto.AAD.computeLength(AAD)); }
0
Java
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
vulnerable
public void testGetOperations() { final HttpHeadersBase headers = newEmptyHeaders(); headers.add("Foo", "1"); headers.add("Foo", "2"); assertThat(headers.get("Foo")).isEqualTo("1"); final List<String> values = headers.getAll("Foo"); assertThat(values).containsExactly("1", "2"); }
0
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable