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
private SingleButtonPanel addNewAjaxActionButton(final AjaxCallback ajaxCallback, final String label, final String... classnames) { final AjaxButton button = new AjaxButton("button", form) { private static final long serialVersionUID = -5306532706450731336L; @Override protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form) { csrfTokenHandler.onSubmit(); ajaxCallback.callback(target); } @Override protected void onError(final AjaxRequestTarget target, final Form< ? > form) { if (ajaxCallback instanceof AjaxFormSubmitCallback) { ((AjaxFormSubmitCallback) ajaxCallback).onError(target, form); } } }; final SingleButtonPanel buttonPanel = new SingleButtonPanel(this.actionButtons.newChildId(), button, label, classnames); buttonPanel.add(button); return buttonPanel; }
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 testInvalidUserIds() { testInvalidUserId("John<b>Doe</b>",true); testInvalidUserId("Jane'Doe'",true); testInvalidUserId("John&Doe",true); testInvalidUserId("Jane\"\"Doe",true); }
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 TMap readMapBegin() throws TException { int size = readVarint32(); byte keyAndValueType = size == 0 ? 0 : readByte(); return new TMap( getTType((byte) (keyAndValueType >> 4)), getTType((byte) (keyAndValueType & 0xf)), size); }
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 String extractCorsOrigin(String pOrigin) { if (pOrigin != null) { // Prevent HTTP response splitting attacks String origin = pOrigin.replaceAll("[\\n\\r]*",""); if (backendManager.isOriginAllowed(origin,false)) { return "null".equals(origin) ? "*" : origin; } else { return null; } } return null; }
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 testGetShellCommandLineNonWindows() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( "/usr/bin" ); cmd.addArguments( new String[] { "a", "b" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( "Command line size", 3, shellCommandline.length ); assertEquals( "/bin/sh", shellCommandline[0] ); assertEquals( "-c", shellCommandline[1] ); if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { assertEquals( "\\usr\\bin a b", shellCommandline[2] ); } else { assertEquals( "/usr/bin a b", shellCommandline[2] ); } }
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
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { String oldName = request.getParameter("groupName"); String newName = request.getParameter("newName"); if (newName != null && newName.matches(".*[&<>\"`']+.*")) { throw new ServletException("Group ID must not contain any HTML markup."); } if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) { m_groupRepository.renameGroup(oldName, newName); } return listGroups(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 testImportZipSigConsumerNotZip() throws IOException, ImporterException { Importer i = new Importer(null, null, null, null, null, null, null, null, config, null, null, null, i18n); Owner owner = mock(Owner.class); ConflictOverrides co = mock(ConflictOverrides.class); File archive = new File("/tmp/file.zip"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive)); out.putNextEntry(new ZipEntry("signature")); out.write("This is the placeholder for the signature file".getBytes()); File ceArchive = new File("/tmp/consumer_export.zip"); FileOutputStream fos = new FileOutputStream(ceArchive); fos.write("This is just a flat file".getBytes()); fos.close(); addFileToArchive(out, ceArchive); out.close(); try { i.loadExport(owner, archive, co); } catch (ImportExtractionException e) { assertEquals(e.getMessage(), i18n.tr("The archive {0} is " + "not a properly compressed file or is empty", "consumer_export.zip")); return; } assertTrue(false); }
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 setSetContentFromFileExceptionally() throws Exception { final long maxSize = 4; DiskFileUpload f1 = new DiskFileUpload("file5", "file5", "application/json", null, null, 0); f1.setMaxSize(maxSize); try { f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize])); File originalFile = f1.getFile(); assertNotNull(originalFile); assertEquals(maxSize, originalFile.length()); assertEquals(maxSize, f1.length()); byte[] bytes = new byte[8]; PlatformDependent.threadLocalRandom().nextBytes(bytes); File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); tmpFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmpFile); try { fos.write(bytes); fos.flush(); } finally { fos.close(); } try { f1.setContent(tmpFile); fail("should not reach here!"); } catch (IOException e) { assertNotNull(f1.getFile()); assertEquals(originalFile, f1.getFile()); assertEquals(maxSize, f1.length()); } } finally { f1.delete(); } }
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
void afterClearHeadersShouldBeEmpty() { final HttpHeadersBase headers = newEmptyHeaders(); headers.add("name1", "value1"); headers.add("name2", "value2"); assertThat(headers.size()).isEqualTo(2); headers.clear(); assertThat(headers.size()).isEqualTo(0); assertThat(headers.isEmpty()).isTrue(); assertThat(headers.contains("name1")).isFalse(); assertThat(headers.contains("name2")).isFalse(); }
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 checkParams() throws Exception { if (vi == null) { throw new Exception("no layers defined."); } if (vi.length > 1) { for (int i = 0; i < vi.length - 1; i++) { if (vi[i] >= vi[i + 1]) { throw new Exception( "v[i] has to be smaller than v[i+1]"); } } } else { throw new Exception( "Rainbow needs at least 1 layer, such that v1 < v2."); } }
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 OldECIESwithDESedeCBC() { super(new CBCBlockCipher(new DESedeEngine()), 8); }
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
void testOfCharSequence() { // Should produce a lower-cased AsciiString. assertThat((Object) HttpHeaderNames.of("Foo")).isEqualTo(AsciiString.of("foo")); // Should reuse known header name instances. assertThat((Object) HttpHeaderNames.of("date")).isSameAs(HttpHeaderNames.DATE); }
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
protected int run() throws Exception { Jenkins h = Jenkins.getInstance(); h.checkPermission(Item.CREATE); if (h.getItemByFullName(name)!=null) { stderr.println("Job '"+name+"' already exists"); return -1; } ModifiableTopLevelItemGroup ig = h; int i = name.lastIndexOf('/'); if (i > 0) { String group = name.substring(0, i); Item item = h.getItemByFullName(group); if (item == null) { throw new IllegalArgumentException("Unknown ItemGroup " + group); } if (item instanceof ModifiableTopLevelItemGroup) { ig = (ModifiableTopLevelItemGroup) item; } else { throw new IllegalArgumentException("Can't create job from CLI in " + group); } name = name.substring(i + 1); } Jenkins.checkGoodName(name); ig.createProjectFromXML(name, stdin); return 0; }
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 doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { try { final URI uri = new URI( request.getParameter( "path" ) ); if ( !validateAccess( uri, response ) ) { return; } final Path path = ioService.get( uri ); byte[] bytes = ioService.readAllBytes( path ); response.setHeader( "Content-Disposition", format( "attachment; filename=%s;", path.getFileName().toString() ) ); response.setContentType( "application/octet-stream" ); response.getOutputStream().write( bytes, 0, bytes.length ); } catch ( final Exception e ) { logger.error( "Failed to download a file.", e ); } }
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
private Document parseXml(String xmlContent) { try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xmlContent))); document.getDocumentElement().normalize(); return document; } catch (Exception e) { throw new JadxRuntimeException("Can not parse xml content", 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
public Entry<P> addPrimitive(final P primitive, Keyset.Key key) throws GeneralSecurityException { if (key.getStatus() != KeyStatusType.ENABLED) { throw new GeneralSecurityException("only ENABLED key is allowed"); } Entry<P> entry = new Entry<P>( primitive, CryptoFormat.getOutputPrefix(key), key.getStatus(), key.getOutputPrefixType(), key.getKeyId()); List<Entry<P>> list = new ArrayList<Entry<P>>(); list.add(entry); // Cannot use [] as keys in hash map, convert to string. String identifier = new String(entry.getIdentifier(), UTF_8); List<Entry<P>> existing = primitives.put(identifier, Collections.unmodifiableList(list)); if (existing != null) { List<Entry<P>> newList = new ArrayList<Entry<P>>(); newList.addAll(existing); newList.add(entry); primitives.put(identifier, Collections.unmodifiableList(newList)); } return entry; }
0
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
vulnerable
public Object unmarshal(InputSource source) throws JAXBException { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xmlReader = sp.getXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/validation", false); xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false); xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); xmlReader.setFeature("http://xml.org/sax/features/namespaces", true); SAXSource saxSource = new SAXSource(xmlReader, source); return delegate.unmarshal(saxSource); } catch (SAXException e) { throw new JAXBException(e); } catch (ParserConfigurationException e) { throw new JAXBException(e); } }
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 void testEqualsInsertionOrderDifferentHeaderNames() { final HttpHeadersBase h1 = newEmptyHeaders(); h1.add("a", "b"); h1.add("c", "d"); final HttpHeadersBase h2 = newEmptyHeaders(); h2.add("c", "d"); h2.add("a", "b"); assertThat(h1).isEqualTo(h2); }
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 addViolation(String propertyName, Integer index, String message) { violationOccurred = true; String messageTemplate = escapeEl(message); context.buildConstraintViolationWithTemplate(messageTemplate) .addPropertyNode(propertyName) .addBeanNode().inIterable().atIndex(index) .addConstraintViolation(); }
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 testHeaderNameStartsWithControlChar1c() { testHeaderNameStartsWithControlChar(0x1c); }
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 void submoduleAdd(String repoUrl, String submoduleNameToPutInGitSubmodules, String folder) { String[] addSubmoduleWithSameNameArgs = new String[]{"submodule", "add", repoUrl, folder}; String[] changeSubmoduleNameInGitModules = new String[]{"config", "--file", ".gitmodules", "--rename-section", "submodule." + folder, "submodule." + submoduleNameToPutInGitSubmodules}; String[] addGitModules = new String[]{"add", ".gitmodules"}; runOrBomb(gitWd().withArgs(addSubmoduleWithSameNameArgs)); runOrBomb(gitWd().withArgs(changeSubmoduleNameInGitModules)); runOrBomb(gitWd().withArgs(addGitModules)); }
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 doesNotPrefixUnsageJpaSortFunctionCalls() { JpaSort sort = JpaSort.unsafe("sum(foo)"); assertThat(applySorting("select p from Person p", sort, "p"), endsWith("order by sum(foo) 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
private void putSomeOldData(File dir) throws Exception { File xml = new File(dir, "foo.xml"); FileUtils.writeStringToFile(xml,"<foo>" + encryptOld(TEST_KEY) + "</foo>"); }
1
Java
NVD-CWE-noinfo
null
null
null
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
public void testRejectECJWKWithUnsupportedCurve() throws Exception { KeyPair keyPair = createUnsupportedECKeyPair(); ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic(); ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate(); ECKey ecJWK = new ECKey.Builder(new ECKey.Curve("P-224"), ecPublicKey).privateKey(ecPrivateKey).build(); try { new ECDHEncrypter(ecJWK); fail(); } catch (JOSEException e) { // ok } try { new ECDHDecrypter(ecJWK); fail(); } catch (JOSEException e) { // ok } }
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 String resolveAction() throws JspException { String action = getAction(); String servletRelativeAction = getServletRelativeAction(); if (StringUtils.hasText(action)) { action = getDisplayString(evaluate(ACTION_ATTRIBUTE, action)); return processAction(action); } else if (StringUtils.hasText(servletRelativeAction)) { String pathToServlet = getRequestContext().getPathToServlet(); if (servletRelativeAction.startsWith("/") && !servletRelativeAction.startsWith(getRequestContext().getContextPath())) { servletRelativeAction = pathToServlet + servletRelativeAction; } servletRelativeAction = getDisplayString(evaluate(ACTION_ATTRIBUTE, servletRelativeAction)); return processAction(servletRelativeAction); } else { String requestUri = getRequestContext().getRequestUri(); String encoding = pageContext.getResponse().getCharacterEncoding(); try { requestUri = UriUtils.encodePath(requestUri, encoding); } catch (UnsupportedEncodingException e) { throw new JspException(e); } ServletResponse response = this.pageContext.getResponse(); if (response instanceof HttpServletResponse) { requestUri = ((HttpServletResponse) response).encodeURL(requestUri); String queryString = getRequestContext().getQueryString(); if (StringUtils.hasText(queryString)) { requestUri += "?" + HtmlUtils.htmlEscape(queryString); } } if (StringUtils.hasText(requestUri)) { return processAction(requestUri); } else { throw new IllegalArgumentException("Attribute 'action' is required. " + "Attempted to resolve against current request URI but request URI was null."); } } }
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
private ECFieldElement generateSquareInput_CarryBug() { int[] x = Nat.create(12); x[0] = RANDOM.nextInt() >>> 1; x[6] = 2; x[10] = -1 << 16; x[11] = -1; return fe(Nat.toBigInteger(12, x)); }
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 Optional<InputStream> getResourceAsStream(String path) { Path filePath = getFilePath(normalize(path)); try { return Optional.of(Files.newInputStream(filePath)); } catch (IOException e) { return Optional.empty(); } }
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 <T> void safelyDissociate(BoundContext<T> context, T storage) { try { context.dissociate(storage); } catch(Exception e) { ServletLogger.LOG.unableToDissociateContext(context, storage); ServletLogger.LOG.catchingDebug(e); } }
1
Java
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))), new FixedSecureRandom.Data(Hex.decode("01020304")) }); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } }
1
Java
CWE-361
7PK - Time and State
This category represents one of the phyla in the Seven Pernicious Kingdoms vulnerability classification. It includes weaknesses related to the improper management of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. According to the authors of the Seven Pernicious Kingdoms, "Distributed computation is about time and state. That is, in order for more than one component to communicate, state must be shared, and all that takes time. Most programmers anthropomorphize their work. They think about one thread of control carrying out the entire program in the same way they would if they had to do the job themselves. Modern computers, however, switch between tasks very quickly, and in multi-core, multi-CPU, or distributed systems, two events may take place at exactly the same time. Defects rush to fill the gap between the programmer's model of how a program executes and what happens in reality. These defects are related to unexpected interactions between threads, processes, time, and information. These interactions happen through shared state: semaphores, variables, the file system, and, basically, anything that can store information."
https://cwe.mitre.org/data/definitions/361.html
safe
protected void afterFeaturesReceived() throws NotConnectedException, InterruptedException { StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE); if (startTlsFeature != null) { if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) { notifyConnectionError(new SecurityRequiredByServerException()); return; } if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) { sendNonza(new StartTls()); } } if (getSASLAuthentication().authenticationSuccessful()) { // If we have received features after the SASL has been successfully completed, then we // have also *maybe* received, as it is an optional feature, the compression feature // from the server. maybeCompressFeaturesReceived.reportSuccess(); } }
1
Java
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
public void translate(LoginPluginRequestPacket packet, GeyserSession session) { // A vanilla client doesn't know any PluginMessage in the Login state, so we don't know any either. // Note: Fabric Networking API v1 will not let the client log in without sending this session.sendDownstreamPacket( new LoginPluginResponsePacket(packet.getMessageId(), null) ); }
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 void svgImage(UImageSvg image, double x, double y) { // https://developer.mozilla.org/fr/docs/Web/SVG/Element/image if (hidden == false) { final Element elt = (Element) document.createElement("image"); elt.setAttribute("width", format(image.getWidth())); elt.setAttribute("height", format(image.getHeight())); elt.setAttribute("x", format(x)); elt.setAttribute("y", format(y)); String svg = manageScale(image); final String svgHeader = "<svg height=\"" + (int) (image.getHeight() * scale) + "\" width=\"" + (int) (image.getWidth() * scale) + "\" xmlns=\"http://www.w3.org/2000/svg\" >"; svg = svgHeader + svg.substring(5); final String s = toBase64(svg); elt.setAttribute("xlink:href", "data:image/svg+xml;base64," + s); getG().appendChild(elt); } ensureVisible(x, y); ensureVisible(x + image.getData("width"), y + image.getData("height")); }
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 void getAllReturnsEmptyListForUnknownName() { final HttpHeadersBase headers = newEmptyHeaders(); assertThat(headers.getAll("noname").size()).isEqualTo(0); }
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
void plus() { final PathAndQuery res = parse("/+?a+b=c+d"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/+"); assertThat(res.query()).isEqualTo("a+b=c+d"); final PathAndQuery res2 = parse("/%2b?a%2bb=c%2bd"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/+"); assertThat(res2.query()).isEqualTo("a%2Bb=c%2Bd"); }
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
void checkVerificationCode() throws Exception { when(this.userManager.exists(this.userReference)).thenReturn(true); InternetAddress email = new InternetAddress("[email protected]"); when(this.userProperties.getEmail()).thenReturn(email); String verificationCode = "abcd1245"; BaseObject xObject = mock(BaseObject.class); when(this.userDocument .getXObject(DefaultResetPasswordManager.RESET_PASSWORD_REQUEST_CLASS_REFERENCE)) .thenReturn(xObject); String encodedVerificationCode = "encodedVerificationCode"; when(xObject.getStringValue(DefaultResetPasswordManager.VERIFICATION_PROPERTY)) .thenReturn(encodedVerificationCode); BaseClass baseClass = mock(BaseClass.class); when(xObject.getXClass(context)).thenReturn(baseClass); PasswordClass passwordClass = mock(PasswordClass.class); when(baseClass.get(DefaultResetPasswordManager.VERIFICATION_PROPERTY)).thenReturn(passwordClass); when(passwordClass.getEquivalentPassword(encodedVerificationCode, verificationCode)) .thenReturn(encodedVerificationCode); String newVerificationCode = "foobartest"; when(xWiki.generateRandomString(30)).thenReturn(newVerificationCode); String saveComment = "Save new verification code"; when(this.localizationManager .getTranslationPlain("xe.admin.passwordReset.step2.versionComment.changeValidationKey")) .thenReturn(saveComment); DefaultResetPasswordRequestResponse expected = new DefaultResetPasswordRequestResponse(this.userReference, email, newVerificationCode); assertEquals(expected, this.resetPasswordManager.checkVerificationCode(this.userReference, verificationCode)); verify(this.xWiki).saveDocument(this.userDocument, saveComment, true, context); }
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 byte[] randomBytes(int size) { byte[] random = new byte[size]; sr.nextBytes(random); return random; }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public SAXReader(DocumentFactory factory, boolean validating) { this.factory = factory; this.validating = validating; }
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 withRestrictor() throws InvalidSyntaxException, MalformedObjectNameException { setupRestrictor(new InnerRestrictor(true,false,true,false,true,false,true)); assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.GET)); assertFalse(restrictor.isTypeAllowed(RequestType.EXEC)); assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage")); assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage")); assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Memory"), "gc")); assertFalse(restrictor.isRemoteAccessAllowed("localhost", "127.0.0.1")); assertTrue(restrictor.isOriginAllowed("http://bla.com", false)); }
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 static Path visit(File file, String filename, FileVisitor<Path> visitor) throws IOException, IllegalArgumentException { if(!StringHelper.containsNonWhitespace(filename)) { filename = file.getName(); } Path fPath = null; if(file.isDirectory()) { fPath = file.toPath(); } else if(filename != null && filename.toLowerCase().endsWith(".zip")) { try { fPath = FileSystems.newFileSystem(file.toPath(), null).getPath("/"); } catch (ProviderNotFoundException | ServiceConfigurationError e) { throw new IOException("Unreadable file with .zip extension: " + file, e); } } else { fPath = file.toPath(); } if(fPath != null) { Files.walkFileTree(fPath, visitor); } return fPath; }
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 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 void performTest() throws Exception { byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 }; ASN1Encodable[] values = { new CAST5CBCParameters(testIv, 128), new NetscapeCertType(NetscapeCertType.smime), new VerisignCzagExtension(new DERIA5String("hello")), new IDEACBCPar(testIv), new NetscapeRevocationURL(new DERIA5String("http://test")) }; byte[] data = Base64.decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA=="); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); for (int i = 0; i != values.length; i++) { aOut.writeObject(values[i]); } ASN1Primitive[] readValues = new ASN1Primitive[values.length]; if (!isSameAs(bOut.toByteArray(), data)) { fail("Failed data check"); } ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream aIn = new ASN1InputStream(bIn); for (int i = 0; i != values.length; i++) { ASN1Primitive o = aIn.readObject(); if (!values[i].equals(o)) { fail("Failed equality test for " + o); } if (o.hashCode() != values[i].hashCode()) { fail("Failed hashCode test for " + o); } } shouldFailOnExtraData(); derIntegerTest(); }
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
protected void traceLdapEnv(Properties env) { if (trace) { Properties tmp = new Properties(); tmp.putAll(env); String credentials = tmp.getProperty(Context.SECURITY_CREDENTIALS); String bindCredential = tmp.getProperty(BIND_CREDENTIAL); if (credentials != null && credentials.length() > 0) tmp.setProperty(Context.SECURITY_CREDENTIALS, "***"); if (bindCredential != null && bindCredential.length() > 0) tmp.setProperty(BIND_CREDENTIAL, "***"); log.trace("Logging into LDAP server, env=" + tmp.toString()); } }
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
protected void showCreateContactDialog(final String prefilledJid, final Invite invite) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); EnterJidDialog dialog = EnterJidDialog.newInstance( mActivatedAccounts, getString(R.string.dialog_title_create_contact), getString(R.string.create), prefilledJid, null, invite == null || !invite.hasFingerprints() ); dialog.setOnEnterJidDialogPositiveListener((accountJid, contactJid) -> { if (!xmppConnectionServiceBound) { return false; } final Account account = xmppConnectionService.findAccountByJid(accountJid); if (account == null) { return true; } final Contact contact = account.getRoster().getContact(contactJid); if (invite != null && invite.getName() != null) { contact.setServerName(invite.getName()); } if (contact.isSelf()) { switchToConversation(contact); return true; } else if (contact.showInRoster()) { throw new EnterJidDialog.JidError(getString(R.string.contact_already_exists)); } else { xmppConnectionService.createContact(contact, true); if (invite != null && invite.hasFingerprints()) { xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints()); } switchToConversationDoNotAppend(contact, invite == null ? null : invite.getBody()); return true; } }); dialog.show(ft, FRAGMENT_TAG_DIALOG); }
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 void testReadBytesAndWriteBytesWithFileChannel() throws IOException { File file = PlatformDependent.createTempFile("file-channel", ".tmp", null); RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "rw"); FileChannel channel = randomAccessFile.getChannel(); // channelPosition should never be changed long channelPosition = channel.position(); byte[] bytes = {'a', 'b', 'c', 'd'}; int len = bytes.length; ByteBuf buffer = newBuffer(len); buffer.resetReaderIndex(); buffer.resetWriterIndex(); buffer.writeBytes(bytes); int oldReaderIndex = buffer.readerIndex(); assertEquals(len, buffer.readBytes(channel, 10, len)); assertEquals(oldReaderIndex + len, buffer.readerIndex()); assertEquals(channelPosition, channel.position()); ByteBuf buffer2 = newBuffer(len); buffer2.resetReaderIndex(); buffer2.resetWriterIndex(); int oldWriterIndex = buffer2.writerIndex(); assertEquals(len, buffer2.writeBytes(channel, 10, len)); assertEquals(channelPosition, channel.position()); assertEquals(oldWriterIndex + len, buffer2.writerIndex()); assertEquals('a', buffer2.getByte(0)); assertEquals('b', buffer2.getByte(1)); assertEquals('c', buffer2.getByte(2)); assertEquals('d', buffer2.getByte(3)); buffer.release(); buffer2.release(); } finally { if (randomAccessFile != null) { randomAccessFile.close(); } file.delete(); } }
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 OldECIESwithAES() { super(new AESEngine()); }
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 TSet readSetBegin() throws TException { byte type = readByte(); int size = readI32(); ensureContainerHasEnough(size, type); return new TSet(type, 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 boolean checkMac(byte[] message, byte[] mac) { return Arrays.equals(mac(message),mac); }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { return this.displayCategory(friendlyUrl,ref,model,request,response,locale); }
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
private JpaOrder(Direction direction, String property, NullHandling nullHandling, boolean ignoreCase, boolean unsafe) { super(direction, property, nullHandling); this.ignoreCase = ignoreCase; this.unsafe = unsafe; }
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 testWhitespaceBeforeTransferEncoding01() { String requestStr = "GET /some/path HTTP/1.1\r\n" + " Transfer-Encoding : chunked\r\n" + "Content-Length: 1\r\n" + "Host: netty.io\r\n\r\n" + "a"; testInvalidHeaders0(requestStr); }
0
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
vulnerable
public void accessDeniedViaOrigin() { expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true); expect(backend.isOriginAllowed("www.jolokia.org",true)).andReturn(false); replay(backend); handler.checkAccess("localhost", "127.0.0.1","www.jolokia.org"); }
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 String getJnlpMac() { return JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(getName()); }
1
Java
NVD-CWE-noinfo
null
null
null
safe
private InterpolationHelper() { }
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 LikeCondition(Selector selector, Parameter<T> parameter) { super(selector, parameter); }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public Document read(InputStream in) throws DocumentException { InputSource source = new InputSource(in); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); }
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(ServerUnloadChunkPacket packet, GeyserSession session) { session.getChunkCache().removeChunk(packet.getX(), packet.getZ()); //Checks if a skull is in an unloaded chunk then removes it Iterator<Vector3i> iterator = session.getSkullCache().keySet().iterator(); while (iterator.hasNext()) { Vector3i position = iterator.next(); if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) { session.getSkullCache().get(position).despawnEntity(session); iterator.remove(); } } // Do the same thing with lecterns iterator = session.getLecternCache().iterator(); while (iterator.hasNext()) { Vector3i position = iterator.next(); if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) { iterator.remove(); } } }
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 Document read(InputSource in) throws DocumentException { try { XMLReader reader = getXMLReader(); reader = installXMLFilter(reader); EntityResolver thatEntityResolver = this.entityResolver; if (thatEntityResolver == null) { thatEntityResolver = createDefaultEntityResolver(in .getSystemId()); this.entityResolver = thatEntityResolver; } reader.setEntityResolver(thatEntityResolver); SAXContentHandler contentHandler = createContentHandler(reader); contentHandler.setEntityResolver(thatEntityResolver); contentHandler.setInputSource(in); boolean internal = isIncludeInternalDTDDeclarations(); boolean external = isIncludeExternalDTDDeclarations(); contentHandler.setIncludeInternalDTDDeclarations(internal); contentHandler.setIncludeExternalDTDDeclarations(external); contentHandler.setMergeAdjacentText(isMergeAdjacentText()); contentHandler.setStripWhitespaceText(isStripWhitespaceText()); contentHandler.setIgnoreComments(isIgnoreComments()); reader.setContentHandler(contentHandler); configureReader(reader, contentHandler); reader.parse(in); return contentHandler.getDocument(); } catch (Exception e) { if (e instanceof SAXParseException) { // e.printStackTrace(); SAXParseException parseException = (SAXParseException) e; String systemId = parseException.getSystemId(); if (systemId == null) { systemId = ""; } String message = "Error on line " + parseException.getLineNumber() + " of document " + systemId + " : " + parseException.getMessage(); throw new DocumentException(message, e); } else { 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
public void destroy(ClassLoader classLoader) { _classLoaderHelperUtilities.remove(classLoader); }
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 SslClientCertificateCredential(File certificate, String password) throws IOException { this.password = Secret.fromString(Scrambler.scramble(password)); this.certificate = Secret.fromString(new String(Base64.encode(FileUtils.readFileToByteArray(certificate)))); }
1
Java
CWE-255
Credentials Management Errors
Weaknesses in this category are related to the management of credentials.
https://cwe.mitre.org/data/definitions/255.html
safe
public static AlgorithmMode resolveAlgorithmMode(final JWEAlgorithm alg) throws JOSEException { if (alg.equals(JWEAlgorithm.ECDH_ES)) { return AlgorithmMode.DIRECT; } else if (alg.equals(JWEAlgorithm.ECDH_ES_A128KW) || alg.equals(JWEAlgorithm.ECDH_ES_A192KW) || alg.equals(JWEAlgorithm.ECDH_ES_A256KW)) { return AlgorithmMode.KW; } else { throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm( alg, ECDHCryptoProvider.SUPPORTED_ALGORITHMS)); } }
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 translate(ServerSetSlotPacket packet, GeyserSession session) { if (packet.getWindowId() == 255) { //cursor GeyserItemStack newItem = GeyserItemStack.from(packet.getItem()); session.getPlayerInventory().setCursor(newItem, session); InventoryUtils.updateCursor(session); return; } //TODO: support window id -2, should update player inventory Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId()); if (inventory == null) return; inventory.setStateId(packet.getStateId()); InventoryTranslator translator = session.getInventoryTranslator(); if (translator != null) { if (session.getCraftingGridFuture() != null) { session.getCraftingGridFuture().cancel(false); } session.setCraftingGridFuture(session.scheduleInEventLoop(() -> updateCraftingGrid(session, packet, inventory, translator), 150, TimeUnit.MILLISECONDS)); GeyserItemStack newItem = GeyserItemStack.from(packet.getItem()); if (packet.getWindowId() == 0 && !(translator instanceof PlayerInventoryTranslator)) { // In rare cases, the window ID can still be 0 but Java treats it as valid session.getPlayerInventory().setItem(packet.getSlot(), newItem, session); InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR.updateSlot(session, session.getPlayerInventory(), packet.getSlot()); } else { inventory.setItem(packet.getSlot(), newItem, session); translator.updateSlot(session, inventory, packet.getSlot()); } } }
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 void newDocumentWebHomeFromURLTemplateProviderSpecifiedTerminal() 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); // Mock 1 existing template provider mockExistingTemplateProviders(templateProviderFullName, new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, true); // 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 as terminal and using a template, as specified in the template // provider. verify(mockURLFactory).createURL("X", "Y", "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 int size() { return ByteUtils.bitLength(n.decode()); }
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
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()); }
0
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
vulnerable
private static boolean queryContainsDoubleDots(@Nullable Bytes query) { if (query == null) { return false; } final int length = query.length; boolean lookingForEquals = true; byte b0 = 0; byte b1 = 0; byte b2 = '/'; for (int i = 0; i < length; i++) { byte b3 = query.data[i]; // Treat the delimiters as `/` so that we can use isSlash() for matching them. switch (b3) { case '=': // Treat only the first `=` as `/`, e.g. // - `foo=..` and `foo=../` should be flagged. // - `foo=..=` shouldn't be flagged because `..=` is not a relative path. if (lookingForEquals) { lookingForEquals = false; b3 = '/'; } break; case '&': case ';': b3 = '/'; lookingForEquals = true; break; } // Flag if the last four bytes are `/../` or `/..&` if (b1 == '.' && b2 == '.' && isSlash(b0) && isSlash(b3)) { return true; } b0 = b1; b1 = b2; b2 = b3; } return b1 == '.' && b2 == '.' && isSlash(b0); }
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
void semicolon() { final PathAndQuery res = PathAndQuery.parse("/;?a=b;c=d"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/;"); assertThat(res.query()).isEqualTo("a=b;c=d"); // '%3B' in a query string should never be decoded into ';'. final PathAndQuery res2 = PathAndQuery.parse("/%3b?a=b%3Bc=d"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/;"); assertThat(res2.query()).isEqualTo("a=b%3Bc=d"); }
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 testFilterUri() { final Collection<String> includes = new ArrayList<String>() {{ add( "git://**" ); }}; final Collection<String> excludes = new ArrayList<String>() {{ add( "file://**" ); }}; Assert.assertFalse( filter( includes, excludes, URI.create( "file:///Users/home" ) ) ); Assert.assertTrue( filter( includes, excludes, URI.create( "git://antpathmatcher" ) ) ); Assert.assertTrue( filter( includes, excludes, URI.create( "git://master@antpathmatcher/repo/sss" ) ) ); Assert.assertTrue( filter( Collections.<String>emptyList(), Collections.<String>emptyList(), URI.create( "file:///Users/home" ) ) ); Assert.assertTrue( filter( Collections.<String>emptyList(), Collections.<String>emptyList(), URI.create( "git://master@antpathmatcher/repo/sss" ) ) ); }
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 DefaultFileSystemResourceLoader(Path path) { this.baseDirPath = Optional.of(path); }
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 synchronized <T extends Result> T setResult(Class<T> resultClass) throws SQLException { checkFreed(); initialize(); if (resultClass == null || DOMResult.class.equals(resultClass)) { domResult = new DOMResult(); active = true; return (T) domResult; } else if (SAXResult.class.equals(resultClass)) { try { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(); stringWriter = new StringWriter(); transformerHandler.setResult(new StreamResult(stringWriter)); active = true; return (T) new SAXResult(transformerHandler); } catch (TransformerException te) { throw new PSQLException(GT.tr("Unable to create SAXResult for SQLXML."), PSQLState.UNEXPECTED_ERROR, te); } } else if (StreamResult.class.equals(resultClass)) { stringWriter = new StringWriter(); active = true; return (T) new StreamResult(stringWriter); } else if (StAXResult.class.equals(resultClass)) { stringWriter = new StringWriter(); try { XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xsw = xof.createXMLStreamWriter(stringWriter); active = true; return (T) new StAXResult(xsw); } catch (XMLStreamException xse) { throw new PSQLException(GT.tr("Unable to create StAXResult for SQLXML"), PSQLState.UNEXPECTED_ERROR, xse); } } throw new PSQLException(GT.tr("Unknown XML Result class: {0}", resultClass), PSQLState.INVALID_PARAMETER_TYPE); }
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 BigInteger[] derDecode( byte[] encoding) throws IOException { ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); if (s.size() != 2) { throw new IOException("malformed signature"); } if (!Arrays.areEqual(encoding, s.getEncoded(ASN1Encoding.DER))) { 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
void headersWithDifferentNamesAndValuesShouldNotBeEquivalent() { final HttpHeadersBase h1 = newEmptyHeaders(); h1.set("name1", "value1"); final HttpHeadersBase h2 = newEmptyHeaders(); h2.set("name2", "value2"); assertThat(h1).isNotEqualTo(h2); assertThat(h2).isNotEqualTo(h1); assertThat(h1).isEqualTo(h1); assertThat(h2).isEqualTo(h2); }
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 processTemplate(Writer writer) throws TemplateException { PACLPolicy initialPolicy = PortalSecurityManagerThreadLocal.getPACLPolicy(); try { PortalSecurityManagerThreadLocal.setPACLPolicy(_paclPolicy); return super.processTemplate(writer); } finally { PortalSecurityManagerThreadLocal.setPACLPolicy(initialPolicy); } }
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
protected final void populateUrlAttributeMap(final Map<String, String> urlParameters) { urlParameters.put("pgtUrl", encodeUrl(this.proxyCallbackUrl)); }
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 boolean isValid(String value, ConstraintValidatorContext context) { long longValue = 0; boolean failed = false; String errorMessage = ""; try { longValue = Long.parseLong(value); } catch (NumberFormatException ex) { failed = true; errorMessage = String.format("Invalid integer value: '%s'", value); } if (!failed && longValue < 0) { failed = true; errorMessage = String.format("Expected positive integer value, got: '%s'", value); } if (!failed) { return true; } LOG.warn(errorMessage); context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation(); return false; }
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 boolean isPattern(final String path) { return path.indexOf('*') != -1 || path.indexOf('?') != -1; }
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 translate(ServerPlaySoundPacket packet, GeyserSession session) { String packetSound; if (packet.getSound() instanceof BuiltinSound) { packetSound = ((BuiltinSound) packet.getSound()).getName(); } else if (packet.getSound() instanceof CustomSound) { packetSound = ((CustomSound) packet.getSound()).getName(); } else { session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString()); return; } SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", "")); String playsound; if (soundMapping == null || soundMapping.getPlaysound() == null) { // no mapping session.getConnector().getLogger() .debug("[PlaySound] Defaulting to sound server gave us for " + packet.toString()); playsound = packetSound.replace("minecraft:", ""); } else { playsound = soundMapping.getPlaysound(); } PlaySoundPacket playSoundPacket = new PlaySoundPacket(); playSoundPacket.setSound(playsound); playSoundPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ())); playSoundPacket.setVolume(packet.getVolume()); playSoundPacket.setPitch(packet.getPitch()); session.sendUpstreamPacket(playSoundPacket); }
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 int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (!haskey) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); setup(ad); encryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); ghash.update(ciphertext, ciphertextOffset, length); ghash.pad(ad != null ? ad.length : 0, length); ghash.finish(ciphertext, ciphertextOffset + length, 16); for (int index = 0; index < 16; ++index) ciphertext[ciphertextOffset + length + index] ^= hashKey[index]; return length + 16; }
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
private void headerMultipleContentLengthValidationShouldPropagate(boolean endStream) { LastInboundHandler inboundHandler = new LastInboundHandler(); request.addLong(HttpHeaderNames.CONTENT_LENGTH, 0); request.addLong(HttpHeaderNames.CONTENT_LENGTH, 1); Http2StreamChannel channel = newInboundStream(3, endStream, inboundHandler); try { inboundHandler.checkException(); fail(); } catch (Exception e) { assertThat(e, CoreMatchers.<Exception>instanceOf(StreamException.class)); } assertNull(inboundHandler.readInbound()); assertFalse(channel.isActive()); }
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
void ampersand() { final PathAndQuery res = PathAndQuery.parse("/&?a=1&a=2&b=3"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/&"); assertThat(res.query()).isEqualTo("a=1&a=2&b=3"); // '%26' in a query string should never be decoded into '&'. final PathAndQuery res2 = PathAndQuery.parse("/%26?a=1%26a=2&b=3"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/&"); assertThat(res2.query()).isEqualTo("a=1%26a=2&b=3"); }
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 CBC() { super(new CBCBlockCipher(new AESEngine()), 128); }
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 sendStreamingResponse(HttpExchange pExchange, ParsedUri pParsedUri, JSONStreamAware pJson) throws IOException { Headers headers = pExchange.getResponseHeaders(); if (pJson != null) { headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8"); pExchange.sendResponseHeaders(200, 0); Writer writer = new OutputStreamWriter(pExchange.getResponseBody(), "UTF-8"); String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()); IoUtil.streamResponseAndClose(writer, pJson, callback != null && MimeTypeUtil.isValidCallback(callback) ? callback : null); } else { headers.set("Content-Type", "text/plain"); pExchange.sendResponseHeaders(200,-1); } }
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 Cipher encrypt() { try { Cipher cipher = Secret.getCipher(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, getKey()); return cipher; } catch (GeneralSecurityException e) { throw new AssertionError(e); } }
1
Java
NVD-CWE-noinfo
null
null
null
safe
private BluetoothSocket acceptSocket(String RemoteAddr) throws IOException { BluetoothSocket as = new BluetoothSocket(this); as.mSocketState = SocketState.CONNECTED; FileDescriptor[] fds = mSocket.getAncillaryFileDescriptors(); if (DBG) Log.d(TAG, "socket fd passed by stack fds: " + fds); if(fds == null || fds.length != 1) { Log.e(TAG, "socket fd passed from stack failed, fds: " + fds); as.close(); throw new IOException("bt socket acept failed"); } as.mSocket = new LocalSocket(fds[0]); as.mPfd = new ParcelFileDescriptor(fds[0]); try { as.mSocket.closeExternalFd(); } catch (IOException e) { Log.e(TAG, "closeExternalFd failed"); } as.mSocketIS = as.mSocket.getInputStream(); as.mSocketOS = as.mSocket.getOutputStream(); as.mAddress = RemoteAddr; as.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(RemoteAddr); as.mPort = mPort; return as; }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public void testClearResetsPseudoHeaderDivision() { final HttpHeadersBase http2Headers = newHttp2Headers(); http2Headers.method(HttpMethod.POST); http2Headers.set("some", "value"); http2Headers.clear(); http2Headers.method(HttpMethod.GET); assertThat(http2Headers.names()).containsExactly(HttpHeaderNames.METHOD); assertThat(http2Headers.getAll(HttpHeaderNames.METHOD)).containsExactly("GET"); }
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 void writeFile(Path path, FileItem uploadedItem) throws IOException { if (!ioService.exists(path)) { ioService.createFile(path); } ioService.write(path, IOUtils.toByteArray(uploadedItem.getInputStream())); uploadedItem.getInputStream().close(); }
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 byte[] engineGetIV() { if (engineSpec != null) { return engineSpec.getNonce(); } return null; }
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 TMap readMapBegin() throws TException { return new TMap(readByte(), 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
private DocumentBuilder createDocumentBuilder() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); return factory.newDocumentBuilder(); }
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 urlEncodedValues() { final String ticket = "ST-1-owKEOtYJjg77iHcCQpkl-cas01.example.org%26%73%65%72%76%69%63%65%3d%68%74%74%70%25%33%41%25%32%46%25%32%46%31%32%37%2e%30%2e%30%2e%31%25%32%46%62%6f%72%69%6e%67%25%32%46%23"; final String service = "foobar"; final String url = this.ticketValidator.constructValidationUrl(ticket, service); final String encodedValue = this.ticketValidator.encodeUrl(ticket); assertTrue(url.contains(encodedValue)); assertFalse(url.contains(ticket)); }
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
protected String makeTokenSignature(long tokenExpiryTime, UserDetails userDetails) { String expectedTokenSignature = DigestUtils.md5Hex(userDetails.getUsername() + ":" + tokenExpiryTime + ":" + "N/A" + ":" + getKey()); return expectedTokenSignature; }
0
Java
NVD-CWE-noinfo
null
null
null
vulnerable
public void testInvalidGroupId(final String groupId, final boolean mustFail) { adminPage(); findElementByLink("Configure Users, Groups and On-Call Roles").click(); findElementByLink("Configure Groups").click(); findElementByLink("Add new group").click(); enterText(By.id("groupName"), groupId); enterText(By.id("groupComment"), "SmokeTestComment"); 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 group ID' alert.", e); throw e; } } else { wait.until(ExpectedConditions.elementToBeClickable(By.name("finish"))); } }
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 testDirectContextUsage() throws Exception { assertThat(ConstraintViolations.format(validator.validate(new DirectContextExample()))) .containsExactlyInAnyOrder(FAILED_RESULT); assertThat(TestLoggerFactory.getAllLoggingEvents()) .isEmpty(); }
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 testGetShellCommandLineBash_WithWorkingDirectory() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( "/bin/echo" ); cmd.addArguments( new String[] { "hello world" } ); File root = File.listRoots()[0]; File workingDirectory = new File( root, "path with spaces" ); cmd.setWorkingDirectory( workingDirectory ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( "Command line size", 3, shellCommandline.length ); assertEquals( "/bin/sh", shellCommandline[0] ); assertEquals( "-c", shellCommandline[1] ); String expectedShellCmd = "cd \"" + root.getAbsolutePath() + "path with spaces\" && /bin/echo \'hello world\'"; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = "cd \"" + root.getAbsolutePath() + "path with spaces\" && \\bin\\echo \'hello world\'"; } assertEquals( expectedShellCmd, shellCommandline[2] ); }
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 void initWithCustomAccessRestrictor() throws ServletException { prepareStandardInitialisation(); 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
final void set(CharSequence name, String... values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); final int h = normalizedName.hashCode(); final int i = index(h); remove0(h, i, normalizedName); 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
static __u8 *kye_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { switch (hdev->product) { case USB_DEVICE_ID_KYE_ERGO_525V: /* the fixups that need to be done: * - change led usage page to button for extra buttons * - report size 8 count 1 must be size 1 count 8 for button * bitfield * - change the button usage range to 4-7 for the extra * buttons */ if (*rsize >= 75 && rdesc[61] == 0x05 && rdesc[62] == 0x08 && rdesc[63] == 0x19 && rdesc[64] == 0x08 && rdesc[65] == 0x29 && rdesc[66] == 0x0f && rdesc[71] == 0x75 && rdesc[72] == 0x08 && rdesc[73] == 0x95 && rdesc[74] == 0x01) { hid_info(hdev, "fixing up Kye/Genius Ergo Mouse " "report descriptor\n"); rdesc[62] = 0x09; rdesc[64] = 0x04; rdesc[66] = 0x07; rdesc[72] = 0x01; rdesc[74] = 0x08; } break; case USB_DEVICE_ID_KYE_EASYPEN_I405X: if (*rsize == EASYPEN_I405X_RDESC_ORIG_SIZE) { rdesc = easypen_i405x_rdesc_fixed; *rsize = sizeof(easypen_i405x_rdesc_fixed); } break; case USB_DEVICE_ID_KYE_MOUSEPEN_I608X: if (*rsize == MOUSEPEN_I608X_RDESC_ORIG_SIZE) { rdesc = mousepen_i608x_rdesc_fixed; *rsize = sizeof(mousepen_i608x_rdesc_fixed); } break; case USB_DEVICE_ID_KYE_EASYPEN_M610X: if (*rsize == EASYPEN_M610X_RDESC_ORIG_SIZE) { rdesc = easypen_m610x_rdesc_fixed; *rsize = sizeof(easypen_m610x_rdesc_fixed); } break; case USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104, "Genius Gila Gaming Mouse"); break; case USB_DEVICE_ID_GENIUS_GX_IMPERATOR: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 83, "Genius Gx Imperator Keyboard"); break; case USB_DEVICE_ID_GENIUS_MANTICORE: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104, "Genius Manticore Keyboard"); break; } return rdesc; }
1
Java
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
safe
private ECFieldElement generateSquareInput_OpenSSLBug() { int[] x = Nat256.create(); x[0] = RANDOM.nextInt() >>> 1; x[4] = 2; x[7] = -1; return fe(Nat256.toBigInteger(x)); }
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 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
public AbstractEpsgFactory(final Hints userHints) throws FactoryException { super(MAXIMUM_PRIORITY - 20); // The following hints have no effect on this class behaviour, // but tell to the user what this factory do about axis order. hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE); hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE); hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE); // // We need to obtain our DataSource if (userHints != null) { Object hint = userHints.get(Hints.EPSG_DATA_SOURCE); if (hint instanceof String) { String name = (String) hint; try { dataSource = (DataSource) GeoTools.getInitialContext().lookup(name); } catch (NamingException e) { throw new FactoryException("A EPSG_DATA_SOURCE hint is required:" + e); } hints.put(Hints.EPSG_DATA_SOURCE, dataSource); } else if (hint instanceof DataSource) { dataSource = (DataSource) hint; hints.put(Hints.EPSG_DATA_SOURCE, dataSource); } else { throw new FactoryException("A EPSG_DATA_SOURCE hint is required."); } } else { throw new FactoryException("A EPSG_DATA_SOURCE hint is required."); } }
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