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 AESCMAC() { super(new CMac(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
public ResponseEntity<Resource> fetch(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { return ResponseEntity.notFound().build(); } if(key.contains("../")){ return ResponseEntity.badRequest().build(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().contentType(mediaType).body(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
/*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException { try { String plainText = new String(cipher.doFinal(in), "UTF-8"); if(plainText.endsWith(MAGIC)) return new Secret(plainText.substring(0,plainText.length()-MAGIC.length())); return null; } catch (GeneralSecurityException e) { return null; // if the key doesn't match with the bytes, it can result in BadPaddingException } }
1
Java
NVD-CWE-noinfo
null
null
null
safe
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(), BDS.class)); } this.keyParams = keyBuilder.build(); } catch (ClassNotFoundException e) { throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage()); } }
1
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
safe
public void testPseudoHeadersWithRemovePreservesPseudoIterationOrder() { final HttpHeadersBase headers = newHttp2Headers(); final HttpHeadersBase nonPseudoHeaders = newEmptyHeaders(); for (Map.Entry<AsciiString, String> entry : headers) { if (entry.getKey().isEmpty() || entry.getKey().charAt(0) != ':' && !nonPseudoHeaders.contains(entry.getKey())) { nonPseudoHeaders.add(entry.getKey(), entry.getValue()); } } assertThat(nonPseudoHeaders.isEmpty()).isFalse(); // Remove all the non-pseudo headers and verify for (Map.Entry<AsciiString, String> nonPseudoHeaderEntry : nonPseudoHeaders) { assertThat(headers.remove(nonPseudoHeaderEntry.getKey())).isTrue(); verifyPseudoHeadersFirst(headers); verifyAllPseudoHeadersPresent(headers); } // Add back all non-pseudo headers for (Map.Entry<AsciiString, String> nonPseudoHeaderEntry : nonPseudoHeaders) { headers.add(nonPseudoHeaderEntry.getKey(), "goo"); verifyPseudoHeadersFirst(headers); verifyAllPseudoHeadersPresent(headers); } }
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 TList readListBegin() throws TException { return new TList(readByte(), readI32()); }
0
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
vulnerable
public void resetHandlers() { getDispatchHandler().resetHandlers(); }
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 static AsciiString of(AsciiString name) { final AsciiString lowerCased = name.toLowerCase(); final AsciiString cached = map.get(lowerCased); if (cached != null) { return cached; } return validate(lowerCased); }
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 drawU(UGraphic ug) { ug = ug.apply(backColor.bg()).apply(borderColor); final URectangle rect = new URectangle(dim.getWidth(), dim.getHeight()).rounded(rounded); rect.setDeltaShadow(shadowing); ug.apply(stroke).draw(rect); final double yLine = titleHeight + attributeHeight; ug = ug.apply(imgBackcolor.bg()); final double thickness = stroke.getThickness(); final URectangle inner = new URectangle(dim.getWidth() - 4 * thickness, dim.getHeight() - titleHeight - 4 * thickness - attributeHeight).rounded(rounded); ug.apply(imgBackcolor).apply(new UTranslate(2 * thickness, yLine + 2 * thickness)).draw(inner); if (titleHeight > 0) { ug.apply(stroke).apply(UTranslate.dy(yLine)).draw(ULine.hline(dim.getWidth())); } if (attributeHeight > 0) { ug.apply(stroke).apply(UTranslate.dy(yLine - attributeHeight)).draw(ULine.hline(dim.getWidth())); } }
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 boolean isAvailable() { try { GeoTools.getInitialContext(); return true; } catch (NamingException 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
private String escapeString(final String string) { if (string == null || string.length() == 0) { return "\"\""; } char c = 0; int i; final int len = string.length(); final StringBuilder sb = new StringBuilder(len + 4); String t; sb.append('"'); for (i = 0; i < len; i += 1) { c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': // if (b == '<') { sb.append('\\'); // } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if (c < ' ') { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); }
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 addElement() { Element root = DocumentHelper.createElement("root"); root.addElement("element>name"); }
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
private ServiceStat getRateLimitOpCountStat() throws Throwable { URI managementServiceUri = this.host.getManagementServiceUri(); return this.host.getServiceStats(managementServiceUri) .get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT); }
0
Java
CWE-732
Incorrect Permission Assignment for Critical Resource
The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.
https://cwe.mitre.org/data/definitions/732.html
vulnerable
public void switchToConversationAndQuote(Conversation conversation, String text) { switchToConversation(conversation, text, true, null, false); }
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 static AsciiString create(String name) { return AsciiString.cached(Ascii.toLowerCase(name)); }
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
private BigInteger[] derDecode( byte[] encoding) throws IOException { ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); if (s.size() != 2) { throw new IOException("malformed signature"); } return new BigInteger[]{ ((ASN1Integer)s.getObjectAt(0)).getValue(), ((ASN1Integer)s.getObjectAt(1)).getValue() }; }
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
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { String oldName = request.getParameter("groupName"); String newName = request.getParameter("newName"); if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) { m_groupRepository.renameGroup(oldName, newName); } return listGroups(request, response); }
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 Cipher decrypt(byte[] iv) { try { Cipher cipher = Secret.getCipher(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, getKey(), new IvParameterSpec(iv)); return cipher; } catch (GeneralSecurityException e) { throw new AssertionError(e); } }
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 String findFilter( String url_suffix ) { if( url_suffix == null ) { throw new IllegalArgumentException( "The url_suffix must not be null." ); } CaptureType type = em.find( CaptureType.class, url_suffix ); if( type != null ) { return type.getCaptureFilter(); } return null; }
0
Java
CWE-754
Improper Check for Unusual or Exceptional Conditions
The software does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software.
https://cwe.mitre.org/data/definitions/754.html
vulnerable
public Object methodException( @SuppressWarnings("rawtypes") Class clazz, String method, Exception e) throws Exception { _log.error(e, e); return null; }
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 void testComputeLength() { byte[] aad = new byte[]{0, 1, 2, 3}; // 32 bits byte[] expectedBitLength = new byte[]{0, 0, 0, 0, 0, 0, 0, 32}; assertTrue(Arrays.equals(expectedBitLength, 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 testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable { File file = PlatformDependent.createTempFile("netty-", ".tmp", null); file.deleteOnExit(); final FileOutputStream out = new FileOutputStream(file); out.write(data); out.close(); sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { // Just drop the message. } }); cb.handler(new ChannelInboundHandlerAdapter()); Channel sc = sb.bind().sync().channel(); Channel cc = cb.connect(sc.localAddress()).sync().channel(); // Request file region which is bigger then the underlying file. FileRegion region = new DefaultFileRegion( new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024); assertThat(cc.writeAndFlush(region).await().cause(), CoreMatchers.<Throwable>instanceOf(IOException.class)); cc.close().sync(); sc.close().sync(); }
1
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
safe
public Document read(File file) throws DocumentException { try { /* * We cannot convert the file to an URL because if the filename * contains '#' characters, there will be problems with the URL in * the InputSource (because a URL like * http://myhost.com/index#anchor is treated the same as * http://myhost.com/index) Thanks to Christian Oetterli */ InputSource source = new InputSource(new FileInputStream(file)); if (this.encoding != null) { source.setEncoding(this.encoding); } String path = file.getAbsolutePath(); if (path != null) { // Code taken from Ant FileUtils StringBuffer sb = new StringBuffer("file://"); // add an extra slash for filesystems with drive-specifiers if (!path.startsWith(File.separator)) { sb.append("/"); } path = path.replace('\\', '/'); sb.append(path); source.setSystemId(sb.toString()); } return read(source); } catch (FileNotFoundException e) { throw new DocumentException(e.getMessage(), e); } }
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
private File extract(ArrayList<String> errors, URL source, String prefix, String suffix, File directory) { File target = null; try { FileOutputStream os = null; InputStream is = null; try { target = File.createTempFile(prefix, suffix, directory); is = source.openStream(); if (is != null) { byte[] buffer = new byte[4096]; os = new FileOutputStream(target); int read; while ((read = is.read(buffer)) != -1) { os.write(buffer, 0, read); } chmod("755", target); } target.deleteOnExit(); return target; } finally { close(os); close(is); } } catch (Throwable e) { if( target!=null ) { target.delete(); } errors.add(e.getMessage()); } return null; }
1
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
safe
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // to get values from the login page // HttpSession session=request.getSession(); PrintWriter out = response.getWriter(); int min = 100000; int max = 999999; otp = 5432; Random r = new Random(); otp = r.nextInt(max - min) + min; String userName = request.getParameter("uname"); String password = sha.getSHA(request.getParameter("pass")); String vemail = request.getParameter("vmail"); String recipient = vemail; String subject = "otp verification"; String content = "your otp is: " + otp; // System.out.print(recipient); String resultMessage = ""; // validation if (voterDao.loginValidate(userName, password, vemail)) { // to display the name of logged-in person in home page HttpSession session = request.getSession(); session.setAttribute("username", userName); try { EmailSend.sendEmail(host, port, user, pass, recipient, subject, content); } catch (MessagingException e) { e.printStackTrace(); resultMessage = "There were an error: " + e.getMessage(); } finally { RequestDispatcher rd = request.getRequestDispatcher("OTP.jsp"); rd.include(request, response); out.println("<script type=\"text/javascript\">"); out.println("alert('" + resultMessage + "');"); out.println("</script>"); } } else { RequestDispatcher rd = request.getRequestDispatcher("voterlogin.jsp"); request.setAttribute("loginFailMsg", "Invalid Input ! Enter again !!"); // request.setAttribute("forgotPassMsg", "Forgot password??"); rd.include(request, response); /* * String forgetpass = request.getParameter("forgotPass"); // * System.out.println(forgetpass); if (forgetpass == null) { rd = * request.getRequestDispatcher("resetPassword.jsp"); rd.forward(request, * response); */ } }
0
Java
CWE-759
Use of a One-Way Hash without a Salt
The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software does not also use a salt as part of the input.
https://cwe.mitre.org/data/definitions/759.html
vulnerable
private JpaOrder(Direction direction, String property) { this(direction, property, NullHandling.NATIVE); }
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 getOrderBy() { return orderBy; }
0
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
vulnerable
public static OHttpSessionManager getInstance() { return instance; }
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
private String loginUser(URI hostUri) throws Throwable { URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK); // wait for factory availability this.host.waitForReplicatedFactoryServiceAvailable(usersLink); String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser); URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC); AuthenticationRequest login = new AuthenticationRequest(); login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN; String[] authToken = new String[1]; authToken[0] = null; Date exp = this.host.getTestExpiration(); while (new Date().before(exp)) { Operation loginPost = Operation.createPost(loginUri) .setBody(login) .addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth) .forceRemote() .setCompletion((op, ex) -> { if (ex != null) { this.host.completeIteration(); return; } authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER); this.host.completeIteration(); }); this.host.testStart(1); this.host.send(loginPost); this.host.testWait(); if (authToken[0] != null) { break; } Thread.sleep(250); } if (new Date().after(exp)) { throw new TimeoutException(); } assertNotNull(authToken[0]); return authToken[0]; }
0
Java
CWE-732
Incorrect Permission Assignment for Critical Resource
The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.
https://cwe.mitre.org/data/definitions/732.html
vulnerable
public IESCipher(IESEngine engine, int ivLength) { this.engine = engine; this.ivLength = ivLength; }
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 String getEncoding() { return encoding; }
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
void requestResetPasswordUnexistingUser() { when(this.userReference.toString()).thenReturn("user:Foobar"); when(this.userManager.exists(this.userReference)).thenReturn(false); String exceptionMessage = "User [user:Foobar] doesn't exist"; when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noUser", "user:Foobar")).thenReturn(exceptionMessage); ResetPasswordException resetPasswordException = assertThrows(ResetPasswordException.class, () -> this.resetPasswordManager.requestResetPassword(this.userReference)); assertEquals(exceptionMessage, resetPasswordException.getMessage()); }
0
Java
CWE-640
Weak Password Recovery Mechanism for Forgotten Password
The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.
https://cwe.mitre.org/data/definitions/640.html
vulnerable
public void getPermissions() { List<String> permissions = method.getPermissions(); assertThat(permissions).containsExactlyInAnyOrder("net:*", "net:listening", "*:*"); }
0
Java
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
public SAXReader(DocumentFactory factory, boolean validating) { this.factory = factory; this.validating = validating; }
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
private static void createBaloInHomeRepo(HttpURLConnection conn, String modulePathInBaloCache, String moduleNameWithOrg, boolean isNightlyBuild, String newUrl, String contentDisposition) { long responseContentLength = conn.getContentLengthLong(); if (responseContentLength <= 0) { createError("invalid response from the server, please try again"); } String resolvedURI = conn.getHeaderField(RESOLVED_REQUESTED_URI); if (resolvedURI == null || resolvedURI.equals("")) { resolvedURI = newUrl; } String[] uriParts = resolvedURI.split("/"); String moduleVersion = uriParts[uriParts.length - 3]; validateModuleVersion(moduleVersion); String baloFile = getBaloFileName(contentDisposition, uriParts[uriParts.length - 1]); Path baloCacheWithModulePath = Paths.get(modulePathInBaloCache, moduleVersion); //<user.home>.ballerina/balo_cache/<org-name>/<module-name>/<module-version> Path baloPath = Paths.get(baloCacheWithModulePath.toString(), baloFile); if (baloPath.toFile().exists()) { createError("module already exists in the home repository: " + baloPath.toString()); } createBaloFileDirectory(baloCacheWithModulePath); writeBaloFile(conn, baloPath, moduleNameWithOrg + ":" + moduleVersion, responseContentLength); handleNightlyBuild(isNightlyBuild, baloCacheWithModulePath); }
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
public TMap readMapBegin() throws TException { byte keyType = readByte(); byte valueType = readByte(); int size = readI32(); ensureMapHasEnough(size, keyType, valueType); return new TMap(keyType, valueType, size); }
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 void headerPlusSignContentLengthValidationShouldPropagate() { headerSignContentLengthValidationShouldPropagateWithEndStream(false, false); }
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 ResponseEntity<Resource> download(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { return ResponseEntity.notFound().build(); } if(key.contains("../")){ return ResponseEntity.badRequest().build(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(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
public static int safeBitLength(final int byteLength) throws IntegerOverflowException { long longResult = (long)byteLength * (long)8; if((long)((int)longResult) != longResult) { throw new IntegerOverflowException(); } else { return (int)longResult; } }
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 static void closeSubsequentFS(Path path) { if(path != null && FileSystems.getDefault() != path.getFileSystem()) { IOUtils.closeQuietly(path.getFileSystem()); } }
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
protected final void _decodeNonStringName(int ch) throws IOException { final int type = ((ch >> 5) & 0x7); String name; if (type == CBORConstants.MAJOR_TYPE_INT_POS) { name = _numberToName(ch, false); } else if (type == CBORConstants.MAJOR_TYPE_INT_NEG) { name = _numberToName(ch, true); } else if (type == CBORConstants.MAJOR_TYPE_BYTES) { /* 08-Sep-2014, tatu: As per [Issue#5], there are codecs * (f.ex. Perl module "CBOR::XS") that use Binary data... */ final int blen = _decodeExplicitLength(ch & 0x1F); byte[] b = _finishBytes(blen); // TODO: Optimize, if this becomes commonly used & bottleneck; we have // more optimized UTF-8 codecs available. name = new String(b, UTF8); } else { if ((ch & 0xFF) == CBORConstants.INT_BREAK) { _reportUnexpectedBreak(); } throw _constructError("Unsupported major type ("+type+") for CBOR Objects, not (yet?) supported, only Strings"); } _parsingContext.setCurrentName(name); }
0
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
vulnerable
public void newDocumentWebHomeButTerminalFromURL() 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); // Pass the tocreate=terminal request parameter when(mockRequest.getParameter("tocreate")).thenReturn("terminal"); // 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 instead of X.Y.WebHome because the tocreate parameter says "terminal". 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 LookAheadObjectInputStream(InputStream in) throws IOException { super(in); }
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 XMLGregorianCalendar toXMLGregorianCalendar(ZonedDateTime instant) { if (instant == null) { return null; } return new XMLGregorianCalendarImpl(GregorianCalendar.from(instant)); }
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 void testUnknownCurve() { try { new ECKey.Builder(new ECKey.Curve("unknown"), ExampleKeyP256.X, ExampleKeyP256.Y).build(); fail(); } catch (IllegalStateException e) { assertEquals("Unknown / unsupported curve: unknown", e.getMessage()); } }
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
void requestResetPassword() throws Exception { when(this.authorizationManager.hasAccess(Right.PROGRAM)).thenReturn(true); UserReference userReference = mock(UserReference.class); ResetPasswordRequestResponse requestResponse = mock(ResetPasswordRequestResponse.class); when(this.resetPasswordManager.requestResetPassword(userReference)).thenReturn(requestResponse); InternetAddress userEmail = new InternetAddress("[email protected]"); when(requestResponse.getUserEmail()).thenReturn(userEmail); assertEquals(userEmail, this.scriptService.requestResetPassword(userReference)); verify(this.resetPasswordManager).sendResetPasswordEmailRequest(requestResponse); }
0
Java
CWE-640
Weak Password Recovery Mechanism for Forgotten Password
The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.
https://cwe.mitre.org/data/definitions/640.html
vulnerable
public void corsWildCard() { InputStream is = getClass().getResourceAsStream("/allow-origin2.xml"); PolicyRestrictor restrictor = new PolicyRestrictor(is); assertTrue(restrictor.isCorsAccessAllowed("http://bla.com")); assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org")); assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de")); }
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 void setHeadersShouldOnlyOverwriteHeaders() { final HttpHeadersBase headers1 = newEmptyHeaders(); headers1.add("name", "value"); headers1.add("name1", "value1"); final HttpHeadersBase headers2 = newEmptyHeaders(); headers2.add("name", "newvalue"); headers2.add("name2", "value2"); final HttpHeadersBase expected = newEmptyHeaders(); expected.add("name", "newvalue"); expected.add("name1", "value1"); expected.add("name2", "value2"); headers1.set(headers2); assertThat(expected).isEqualTo(headers1); }
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 Object deserialize(final String s) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes("8859_1"))); return ois.readObject(); } catch (Exception e) { logger.error("Cannot deserialize payload using " + (s == null ? -1 : s.length()) + " bytes", e); throw new IllegalArgumentException("Cannot deserialize payload"); } finally { if (ois != null) { try { ois.close(); } catch (IOException ignore) { // empty catch block } } } }
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 consecutiveSlashes() { final PathAndQuery res = parse( "/path//with///consecutive////slashes?/query//with///consecutive////slashes"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/path/with/consecutive/slashes"); assertThat(res.query()).isEqualTo("/query//with///consecutive////slashes"); // Encoded slashes final PathAndQuery res2 = parse( "/path%2F/with/%2F/consecutive//%2F%2Fslashes?/query%2F/with/%2F/consecutive//%2F%2Fslashes"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/path%2F/with/%2F/consecutive/%2F%2Fslashes"); assertThat(res2.query()).isEqualTo("/query%2F/with/%2F/consecutive//%2F%2Fslashes"); }
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 int read() throws IOException { return inner.read(); }
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 boolean isActivated() { return needed.isOn(); }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public Object getResourceDataForKey(String key) { Object data = null; String dataString = null; Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(key); if (matcher.find()) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage( Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key, dataString)); } int dataStart = matcher.end(); dataString = key.substring(dataStart); byte[] objectArray = null; byte[] dataArray; try { dataArray = dataString.getBytes("ISO-8859-1"); objectArray = decrypt(dataArray); } catch (UnsupportedEncodingException e1) { // default encoding always presented. } if ("B".equals(matcher.group(1))) { data = objectArray; } else { try { ObjectInputStream in = new LookAheadObjectInputStream(new ByteArrayInputStream(objectArray)); data = in.readObject(); } catch (StreamCorruptedException e) { log.error(Messages .getMessage(Messages.STREAM_CORRUPTED_ERROR), e); } catch (IOException e) { log.error(Messages .getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR), e); } catch (ClassNotFoundException e) { log .error( Messages .getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR), e); } } } return data; }
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 static boolean appendOneByte(Bytes buf, int cp, boolean wasSlash, boolean isPath) { if (cp == 0x7F) { // Reject the control character: 0x7F return false; } if (cp >>> 5 == 0) { // Reject the control characters: 0x00..0x1F if (isPath) { return false; } else if (cp != 0x0A && cp != 0x0D && cp != 0x09) { // .. except 0x0A (LF), 0x0D (CR) and 0x09 (TAB) because they are used in a form. return false; } } if (cp == '/' && isPath) { if (!wasSlash) { buf.ensure(1); buf.add((byte) '/'); } else { // Remove the consecutive slashes: '/path//with///consecutive////slashes'. } } else { final BitSet allowedChars = isPath ? ALLOWED_PATH_CHARS : ALLOWED_QUERY_CHARS; buf.ensure(1); if (allowedChars.get(cp)) { buf.add((byte) cp); } else { buf.addEncoded((byte) cp); } } return 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
protected void initOther() throws ServletException { PropertyUtils.addBeanIntrospector( SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS); PropertyUtils.clearDescriptors(); String value = null; value = getServletConfig().getInitParameter("config"); if (value != null) { config = value; } // Backwards compatibility for form beans of Java wrapper classes // Set to true for strict Struts 1.0 compatibility value = getServletConfig().getInitParameter("convertNull"); if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) { convertNull = true; } if (convertNull) { ConvertUtils.deregister(); ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class); ConvertUtils.register(new BooleanConverter(null), Boolean.class); ConvertUtils.register(new ByteConverter(null), Byte.class); ConvertUtils.register(new CharacterConverter(null), Character.class); ConvertUtils.register(new DoubleConverter(null), Double.class); ConvertUtils.register(new FloatConverter(null), Float.class); ConvertUtils.register(new IntegerConverter(null), Integer.class); ConvertUtils.register(new LongConverter(null), Long.class); ConvertUtils.register(new ShortConverter(null), Short.class); } }
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 doesNotPrefixAliasedFunctionCallNameWhenQueryStringContainsMultipleWhiteSpaces() { String query = "SELECT AVG( m.price ) AS avgPrice FROM Magazine m"; Sort sort = new Sort("avgPrice"); assertThat(applySorting(query, sort, "m"), endsWith("order by avgPrice 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 boolean isCorsAccessAllowed(String pOrigin) { return checkRestrictorService(CORS_CHECK,pOrigin); }
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
private void updateSecureSessionFlag() { try { ServletContext context = Jenkins.getInstance().servletContext; 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); Method setSecure = scc.getMethod("setSecure",boolean.class); boolean v = fixNull(jenkinsUrl).startsWith("https"); setSecure.invoke(sessionCookieConfig,v); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to set secure cookie flag", e); } }
0
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
vulnerable
private void verifyRewrite(File dir) throws Exception { File xml = new File(dir, "foo.xml"); assertEquals("<foo>" + encryptNew(TEST_KEY) + "</foo>".trim(), FileUtils.readFileToString(xml).trim()); }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public void translate(ServerSpawnPositionPacket packet, GeyserSession session) { SetSpawnPositionPacket spawnPositionPacket = new SetSpawnPositionPacket(); spawnPositionPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ())); spawnPositionPacket.setSpawnForced(true); spawnPositionPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension())); spawnPositionPacket.setSpawnType(SetSpawnPositionPacket.Type.WORLD_SPAWN); session.sendUpstreamPacket(spawnPositionPacket); }
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 synchronized MultiMap headers() { if (headers == null) { headers = new CaseInsensitiveHeaders(); } return headers; }
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 testBasicWorkflow() throws Exception { putSomeOldData(jenkins.getRootDir()); WebClient wc = createWebClient(); // one should see the warning. try scheduling it assertTrue(!monitor.isScanOnBoot()); HtmlForm form = getRekeyForm(wc); submit(form, "schedule"); assertTrue(monitor.isScanOnBoot()); form = getRekeyForm(wc); assertTrue(getButton(form, 1).isDisabled()); // run it now assertTrue(!monitor.getLogFile().exists()); submit(form, "background"); assertTrue(monitor.getLogFile().exists()); // should be no warning/error now HtmlPage manage = wc.goTo("/manage"); assertEquals(0,manage.selectNodes("//*[class='error']").size()); assertEquals(0,manage.selectNodes("//*[class='warning']").size()); // and the data should be rewritten verifyRewrite(jenkins.getRootDir()); assertTrue(monitor.isDone()); // dismiss and the message will be gone assertTrue(monitor.isEnabled()); form = getRekeyForm(wc); submit(form, "dismiss"); assertFalse(monitor.isEnabled()); try { getRekeyForm(wc); fail(); } catch (ElementNotFoundException e) { // expected } }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public void headerMultipleContentLengthValidationShouldPropagateWithEndStream() { headerMultipleContentLengthValidationShouldPropagate(true); }
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 Map<String, Object> getHelperUtilities() { Map<String, Object> helperUtilities = super.getHelperUtilities(); // Enum util helperUtilities.put( "enumUtil", BeansWrapper.getDefaultInstance().getEnumModels()); // Object util helperUtilities.put("objectUtil", new ObjectConstructor()); // Portlet preferences helperUtilities.put( "freeMarkerPortletPreferences", new TemplatePortletPreferences()); // Static class util helperUtilities.put( "staticUtil", BeansWrapper.getDefaultInstance().getStaticModels()); return helperUtilities; }
0
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
vulnerable
for (int i = 0; i < reservedChars.length(); i++) { RESERVED_CHARS.set(reservedChars.charAt(i)); }
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 File createTempFile(String prefix, String suffix, File directory) throws IOException { if (javaVersion() >= 7) { if (directory == null) { return Files.createTempFile(prefix, suffix).toFile(); } return Files.createTempFile(directory.toPath(), prefix, suffix).toFile(); } if (directory == null) { return File.createTempFile(prefix, suffix); } File file = File.createTempFile(prefix, suffix, directory); // Try to adjust the perms, if this fails there is not much else we can do... file.setReadable(false, false); file.setReadable(true, true); return file; }
1
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
safe
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception { // We're sending an XML response, so set the response content type to text/xml response.setContentType("text/xml"); // Parse the incoming request as XML SAXReader xmlReader = XML.getSafeSaxReader(); Document doc = xmlReader.read(request.getInputStream()); Element env = doc.getRootElement(); Element body = env.element("body"); // First handle any new subscriptions List<SubscriptionRequest> requests = new ArrayList<SubscriptionRequest>(); List<Element> elements = body.elements("subscribe"); for (Element e : elements) { requests.add(new SubscriptionRequest(e.attributeValue("topic"))); } ServletLifecycle.beginRequest(request); try { ServletContexts.instance().setRequest(request); Manager.instance().initializeTemporaryConversation(); ServletLifecycle.resumeConversation(request); for (SubscriptionRequest req : requests) { req.subscribe(); } // Then handle any unsubscriptions List<String> unsubscribeTokens = new ArrayList<String>(); elements = body.elements("unsubscribe"); for (Element e : elements) { unsubscribeTokens.add(e.attributeValue("token")); } for (String token : unsubscribeTokens) { RemoteSubscriber subscriber = SubscriptionRegistry.instance(). getSubscription(token); if (subscriber != null) { subscriber.unsubscribe(); } } } finally { Lifecycle.endRequest(); } // Package up the response marshalResponse(requests, response.getOutputStream()); }
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 File loadOrDownload(String databaseType, String driverFileUrl) { String filePath = driverFilePath(driverBaseDirectory, databaseType); Path path = Path.of(filePath); if (Files.exists(path)) { // ignore log.debug("{} already exists, ignore download from {}", filePath, driverFileUrl); return path.toFile(); } return this.doDownload(driverFileUrl, filePath); }
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 XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); }
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 CorsChecker(Document pDoc) { NodeList corsNodes = pDoc.getElementsByTagName("cors"); if (corsNodes.getLength() > 0) { patterns = new ArrayList<Pattern>(); for (int i = 0; i < corsNodes.getLength(); i++) { Node corsNode = corsNodes.item(i); NodeList nodes = corsNode.getChildNodes(); for (int j = 0;j <nodes.getLength();j++) { Node node = nodes.item(j); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } assertNodeName(node,"allow-origin"); String p = node.getTextContent().trim().toLowerCase(); p = Pattern.quote(p).replace("*","\\E.*\\Q"); patterns.add(Pattern.compile("^" + p + "$")); } } } }
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 SAXReader(XMLReader xmlReader, boolean validating) { this.xmlReader = xmlReader; this.validating = validating; }
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
void testPseudoHeadersWithRemovePreservesPseudoIterationOrder() { final HttpHeadersBase headers = newHttp2Headers(); final HttpHeadersBase nonPseudoHeaders = newEmptyHeaders(); for (Map.Entry<AsciiString, String> entry : headers) { if (entry.getKey().isEmpty() || entry.getKey().charAt(0) != ':' && !nonPseudoHeaders.contains(entry.getKey())) { nonPseudoHeaders.add(entry.getKey(), entry.getValue()); } } assertThat(nonPseudoHeaders.isEmpty()).isFalse(); // Remove all the non-pseudo headers and verify for (Map.Entry<AsciiString, String> nonPseudoHeaderEntry : nonPseudoHeaders) { assertThat(headers.remove(nonPseudoHeaderEntry.getKey())).isTrue(); verifyPseudoHeadersFirst(headers); verifyAllPseudoHeadersPresent(headers); } // Add back all non-pseudo headers for (Map.Entry<AsciiString, String> nonPseudoHeaderEntry : nonPseudoHeaders) { headers.add(nonPseudoHeaderEntry.getKey(), "goo"); verifyPseudoHeadersFirst(headers); verifyAllPseudoHeadersPresent(headers); } }
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 testValidUserIds() { testInvalidUserId("John-Doe",false); testInvalidUserId("Jane/Doe",false); testInvalidUserId("John.Doe",false); testInvalidUserId("Jane#Doe", false); testInvalidUserId("John@Döe.com", false); testInvalidUserId("JohnDoé", false); }
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 translate(ServerSetTitlesAnimationPacket packet, GeyserSession session) { SetTitlePacket titlePacket = new SetTitlePacket(); titlePacket.setType(SetTitlePacket.Type.TIMES); titlePacket.setText(""); titlePacket.setFadeInTime(packet.getFadeIn()); titlePacket.setFadeOutTime(packet.getFadeOut()); titlePacket.setStayTime(packet.getStay()); 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 BourneShell( boolean isLoginShell ) { setShellCommand( "/bin/sh" ); setArgumentQuoteDelimiter( '\'' ); setExecutableQuoteDelimiter( '\"' ); setSingleQuotedArgumentEscaped( true ); setSingleQuotedExecutableEscaped( false ); setQuotedExecutableEnabled( true ); setArgumentEscapePattern("'\\%s'"); if ( isLoginShell ) { addShellArg( "-l" ); } }
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 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
public static String getPropertyDef(InputSpec inputSpec, Map<String, Integer> indexes, String pattern, DefaultValueProvider defaultValueProvider) { int index = indexes.get(inputSpec.getName()); StringBuffer buffer = new StringBuffer(); inputSpec.appendField(buffer, index, "String"); inputSpec.appendCommonAnnotations(buffer, index); if (!inputSpec.isAllowEmpty()) buffer.append(" @NotEmpty\n"); if (pattern != null) buffer.append(" @Pattern(regexp=\"" + pattern + "\", message=\"Should match regular expression: " + pattern + "\")\n"); inputSpec.appendMethods(buffer, index, "String", null, defaultValueProvider); return buffer.toString(); }
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 static String malformedHeaderValueMessage(String value) { final StringBuilder buf = new StringBuilder(IntMath.saturatedAdd(value.length(), 64)); buf.append("malformed header value: "); final int valueLength = value.length(); for (int i = 0; i < valueLength; i++) { final char ch = value.charAt(i); if (PROHIBITED_VALUE_CHARS.get(ch)) { buf.append(PROHIBITED_VALUE_CHAR_NAMES[ch]); } else { buf.append(ch); } } return buf.toString(); }
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
private void dataContentLengthInvalid(boolean negative) throws Exception { final ByteBuf data = dummyData(); int padding = 10; int processedBytes = data.readableBytes() + padding; mockFlowControl(processedBytes); try { decode().onHeadersRead(ctx, STREAM_ID, new DefaultHttp2Headers() .setLong(HttpHeaderNames.CONTENT_LENGTH, negative ? -1L : 1L), padding, false); decode().onDataRead(ctx, STREAM_ID, data, padding, true); verify(localFlow).receiveFlowControlledFrame(eq(stream), eq(data), eq(padding), eq(true)); verify(localFlow).consumeBytes(eq(stream), eq(processedBytes)); verify(listener, times(1)).onHeadersRead(eq(ctx), anyInt(), any(Http2Headers.class), eq(0), eq(DEFAULT_PRIORITY_WEIGHT), eq(false), eq(padding), eq(false)); // Verify that the event was absorbed and not propagated to the observer. verify(listener, never()).onDataRead(eq(ctx), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean()); } finally { data.release(); } }
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 ECKey(final Curve crv, final Base64URL x, final Base64URL y, final KeyUse use, final Set<KeyOperation> ops, final Algorithm alg, final String kid, final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List<Base64> x5c, final KeyStore ks) { super(KeyType.EC, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); if (crv == null) { throw new IllegalArgumentException("The curve must not be null"); } this.crv = crv; if (x == null) { throw new IllegalArgumentException("The 'x' coordinate must not be null"); } this.x = x; if (y == null) { throw new IllegalArgumentException("The 'y' coordinate must not be null"); } this.y = y; ensurePublicCoordinatesOnCurve(crv, x, y); this.d = null; this.privateKey = null; }
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 test_notLike_any() { Entity from = from(Entity.class); where(from.getCode()).notLike().any("test"); Query<Entity> select = select(from); assertEquals("select entity_0 from Entity entity_0 where entity_0.code not like :code_1", select.getQuery()); assertEquals("%test%", select.getParameters().get("code_1")); }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public void onTaskSelectionEvent(@Observes TaskSelectionEvent event){ selectedTaskId = event.getTaskId(); selectedTaskName = event.getTaskName(); view.getTaskIdAndName().setText(SafeHtmlUtils.htmlEscape(String.valueOf(selectedTaskId) + " - "+selectedTaskName)); view.getContent().clear(); String placeToGo; if(event.getPlace() != null && !event.getPlace().equals("")){ placeToGo = event.getPlace(); }else{ placeToGo = "Task Details"; } DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo); //Set Parameters here: defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId)); defaultPlaceRequest.addParameter("taskName", selectedTaskName); Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest); AbstractWorkbenchScreenActivity activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next()); activitiesMap.put(placeToGo, activity); IsWidget widget = activity.getWidget(); activity.launch(place, null); activity.onStartup(defaultPlaceRequest); view.getContent().add(widget); activity.onOpen(); }
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 giveWarningIfNoValidationMethods() throws Exception { assertThat(ConstraintViolations.format(validator.validate(new NoValidations()))) .isEmpty(); assertThat(TestLoggerFactory.getAllLoggingEvents()) .containsExactlyInAnyOrder( new LoggingEvent( Level.WARN, "The class {} is annotated with @SelfValidating but contains no valid methods that are annotated with @SelfValidation", NoValidations.class ) ); }
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 handle(final HttpServletRequest request, final HttpServletResponse response) throws Exception { new ContextualHttpServletRequest(request) { @Override public void process() throws Exception { ServletContexts.instance().setRequest(request); if (request.getQueryString() == null) { throw new ServletException("Invalid request - no component specified"); } Set<Component> components = new HashSet<Component>(); Set<Type> types = new HashSet<Type>(); response.setContentType("text/javascript"); Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String componentName = ((String) e.nextElement()).trim(); Component component = Component.forName(componentName); if (component == null) { try { Class c = Reflections.classForName(componentName); appendClassSource(response.getOutputStream(), c, types); } catch (ClassNotFoundException ex) { log.error(String.format("Component not found: [%s]", componentName)); throw new ServletException("Invalid request - component not found."); } } else { components.add(component); } } generateComponentInterface(components, response.getOutputStream(), types); } }.run(); }
0
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
vulnerable
public void testSelectByUse() { JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyUse(KeyUse.ENCRYPTION).build()); List<JWK> keyList = new ArrayList<>(); keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").keyUse(KeyUse.ENCRYPTION).build()); keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()); JWKSet jwkSet = new JWKSet(keyList); List<JWK> matches = selector.select(jwkSet); RSAKey key1 = (RSAKey)matches.get(0); assertEquals(KeyType.RSA, key1.getKeyType()); assertEquals(KeyUse.ENCRYPTION, key1.getKeyUse()); assertEquals("1", key1.getKeyID()); assertEquals(1, matches.size()); }
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
protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound) { int iterations = getNumberOfIterations(bitlength, param.getCertainty()); for (int i = 0; i != 5 * bitlength; i++) { BigInteger p = new BigInteger(bitlength, 1, param.getRandom()); if (p.mod(e).equals(ONE)) { continue; } if (p.multiply(p).compareTo(sqrdBound) < 0) { continue; } if (!isProbablePrime(p, iterations)) { continue; } if (!e.gcd(p.subtract(ONE)).equals(ONE)) { continue; } return p; } throw new IllegalStateException("unable to generate prime number for RSA key"); }
0
Java
CWE-327
Use of a Broken or Risky Cryptographic Algorithm
The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.
https://cwe.mitre.org/data/definitions/327.html
vulnerable
public void translate(ServerOpenHorseWindowPacket packet, GeyserSession session) { Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); if (entity == null) { return; } UpdateEquipPacket updateEquipPacket = new UpdateEquipPacket(); updateEquipPacket.setWindowId((short) packet.getWindowId()); updateEquipPacket.setWindowType((short) ContainerType.HORSE.getId()); updateEquipPacket.setUniqueEntityId(entity.getGeyserId()); NbtMapBuilder builder = NbtMap.builder(); List<NbtMap> slots = new ArrayList<>(); InventoryTranslator inventoryTranslator; if (entity instanceof LlamaEntity) { inventoryTranslator = new LlamaInventoryTranslator(packet.getNumberOfSlots()); slots.add(CARPET_SLOT); } else if (entity instanceof ChestedHorseEntity) { inventoryTranslator = new DonkeyInventoryTranslator(packet.getNumberOfSlots()); slots.add(SADDLE_SLOT); } else { inventoryTranslator = new HorseInventoryTranslator(packet.getNumberOfSlots()); slots.add(SADDLE_SLOT); slots.add(ARMOR_SLOT); } // Build the NbtMap that sets the icons for Bedrock (e.g. sets the saddle outline on the saddle slot) builder.putList("slots", NbtType.COMPOUND, slots); updateEquipPacket.setTag(builder.build()); session.sendUpstreamPacket(updateEquipPacket); session.setInventoryTranslator(inventoryTranslator); InventoryUtils.openInventory(session, new Container(entity.getMetadata().getString(EntityData.NAMETAG), packet.getWindowId(), packet.getNumberOfSlots(), null, session.getPlayerInventory())); }
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 ResponseEntity<Resource> fetch(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { ResponseEntity.notFound(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { ResponseEntity.notFound(); } return ResponseEntity.ok().contentType(mediaType).body(file); }
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
protected final String constructValidationUrl(final String ticket, final String serviceUrl) { final Map<String, String> urlParameters = new HashMap<String, String>(); logger.debug("Placing URL parameters in map."); urlParameters.put("ticket", ticket); urlParameters.put("service", serviceUrl); if (this.renew) { urlParameters.put("renew", "true"); } logger.debug("Calling template URL attribute map."); populateUrlAttributeMap(urlParameters); logger.debug("Loading custom parameters from configuration."); if (this.customParameters != null) { urlParameters.putAll(this.customParameters); } final String suffix = getUrlSuffix(); final StringBuilder buffer = new StringBuilder(urlParameters.size() * 10 + this.casServerUrlPrefix.length() + suffix.length() + 1); int i = 0; buffer.append(this.casServerUrlPrefix); if (!this.casServerUrlPrefix.endsWith("/")) { buffer.append("/"); } buffer.append(suffix); for (Map.Entry<String, String> entry : urlParameters.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (value != null) { buffer.append(i++ == 0 ? "?" : "&"); buffer.append(key); buffer.append("="); final String encodedValue = encodeUrl(value); buffer.append(encodedValue); } } return buffer.toString(); }
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 boolean importWiki(File file, String filename, File targetDirectory) { try { Path path = FileResource.getResource(file, filename); if(path == null) { return false; } Path destDir = targetDirectory.toPath(); Files.walkFileTree(path, new ImportVisitor(destDir)); PathUtils.closeSubsequentFS(path); return true; } catch (IOException e) { log.error("", e); return false; } }
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
private DocumentReferenceResolver<String> getCurrentMixedDocumentReferenceResolver() { return Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, CURRENT_MIXED_RESOLVER_HINT); }
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
private static CharSequenceMap toLowercaseMap(Iterator<? extends CharSequence> valuesIter, int arraySizeHint) { final CharSequenceMap result = new CharSequenceMap(arraySizeHint); while (valuesIter.hasNext()) { final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase(); try { int index = lowerCased.forEachByte(FIND_COMMA); if (index != -1) { int start = 0; do { result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING); start = index + 1; } while (start < lowerCased.length() && (index = lowerCased.forEachByte(start, lowerCased.length() - start, FIND_COMMA)) != -1); result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING); } else { result.add(lowerCased.trim(), EMPTY_STRING); } } catch (Exception e) { // This is not expect to happen because FIND_COMMA never throws but must be caught // because of the ByteProcessor interface. throw new IllegalStateException(e); } } return result; }
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 validateFail4(ViolationCollector col) { col.addViolation("p", "four", 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 static void cleanup() throws Exception { System.clearProperty("java.protocol.handler.pkgs"); stopAllServers(); }
1
Java
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
safe
private JpaSort(List<Order> orders) { super(orders); }
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 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 (keySpec == null) { // 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(); try { setup(ad); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.update(ciphertext, ciphertextOffset, dataLen); ghash.pad(ad != null ? ad.length : 0, dataLen); ghash.finish(iv, 0, 16); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); try { int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset); cipher.doFinal(plaintext, plaintextOffset + result); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } 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 void validate() { final String filter = format(ldapConfiguration.getUserSearchFilter(), "test"); ldapConnectionTemplate.searchFirst(ldapConfiguration.getSearchBases().get(0), filter, SearchScope.SUBTREE, entry -> entry); }
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-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 SecretRewriter(File backupDirectory) throws GeneralSecurityException { cipher = Secret.getCipher("AES"); key = Secret.getLegacyKey(); this.backupDirectory = backupDirectory; }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public void testNoSubjectAlternativeNameCNMatch() throws Exception { SpringBusFactory bf = new SpringBusFactory(); URL busFile = HostnameVerificationDeprecatedTest.class.getResource("hostname-client.xml"); Bus bus = bf.createBus(busFile.toString()); BusFactory.setDefaultBus(bus); BusFactory.setThreadDefaultBus(bus); URL url = SOAPService.WSDL_LOCATION; SOAPService service = new SOAPService(url, SOAPService.SERVICE); assertNotNull("Service is null", service); final Greeter port = service.getHttpsPort(); assertNotNull("Port is null", port); updateAddressPort(port, PORT2); assertEquals(port.greetMe("Kitty"), "Hello Kitty"); // Enable Async ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true); assertEquals(port.greetMe("Kitty"), "Hello Kitty"); ((java.io.Closeable)port).close(); bus.shutdown(true); }
1
Java
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
safe