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
static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source) { Ruby runtime = context.getRuntime(); XmlSchema xmlSchema = (XmlSchema) NokogiriService.XML_SCHEMA_ALLOCATOR.allocate(runtime, klazz); xmlSchema.setInstanceVariable("@errors", runtime.newEmptyArray()); try { SchemaErrorHandler error_handler = new SchemaErrorHandler(context.getRuntime(), (RubyArray)xmlSchema.getInstanceVariable("@errors")); Schema schema = xmlSchema.getSchema(source, context.getRuntime().getCurrentDirectory(), context.getRuntime().getInstanceConfig().getScriptFileName(), error_handler); xmlSchema.setValidator(schema.newValidator()); return xmlSchema; } catch (SAXException ex) { throw context.getRuntime().newRuntimeError("Could not parse document: " + ex.getMessage()); } }
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 void testKeyGeneration(int keysize) throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA", "BC"); generator.initialize(keysize); KeyPair keyPair = generator.generateKeyPair(); DSAPrivateKey priv = (DSAPrivateKey)keyPair.getPrivate(); DSAParams params = priv.getParams(); isTrue("keysize mismatch", keysize == params.getP().bitLength()); // The NIST standard does not fully specify the size of q that // must be used for a given key size. Hence there are differences. // For example if keysize = 2048, then OpenSSL uses 256 bit q's by default, // but the SUN provider uses 224 bits. Both are acceptable sizes. // The tests below simply asserts that the size of q does not decrease the // overall security of the DSA. int qsize = params.getQ().bitLength(); switch (keysize) { case 1024: isTrue("Invalid qsize for 1024 bit key:" + qsize, qsize >= 160); break; case 2048: isTrue("Invalid qsize for 2048 bit key:" + qsize, qsize >= 224); break; case 3072: isTrue("Invalid qsize for 3072 bit key:" + qsize, qsize >= 256); break; default: fail("Invalid key size:" + keysize); } // Check the length of the private key. // For example GPG4Browsers or the KJUR library derived from it use // q.bitCount() instead of q.bitLength() to determine the size of the private key // and hence would generate keys that are much too small. isTrue("privkey error", priv.getX().bitLength() >= qsize - 32); }
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 ECFieldElement generateMultiplyInput_Random() { return fe(new BigInteger(DP.getCurve().getFieldSize() + 32, RANDOM).mod(Q)); }
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 create() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100, 10, 10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 6757, null, 100, 10, 10000); verify(jettyServerFactory, times(1)).create(100, 10, 10000); verifyNoMoreInteractions(jettyServerFactory); }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
private void decodeTest() { EllipticCurve curve = new EllipticCurve( new ECFieldFp(new BigInteger("6277101735386680763835789423207666416083908700390324961279")), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b ECPoint p = ECPointUtil.decodePoint(curve, Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")); if (!p.getAffineX().equals(new BigInteger("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16))) { fail("x uncompressed incorrectly"); } if (!p.getAffineY().equals(new BigInteger("7192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16))) { fail("y uncompressed incorrectly"); } }
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 TestException(List<String> list, EnumSet<IndexShardState> set, Map<String, String> map, InetAddress address, Object[] someArray) { super("foo", null); this.list = list; this.set = set; this.map = map; this.address = address; this.someArray = someArray; }
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
void testSetSelfIsNoOp() { final HttpHeadersBase headers = newEmptyHeaders(); headers.add("name", "value"); headers.set(headers); assertThat(headers.size()).isEqualTo(1); }
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 safelyDeactivate(ManagedContext context, HttpServletRequest request) { try { context.deactivate(); } catch(Exception e) { ServletLogger.LOG.unableToDeactivateContext(context, request); 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
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
protected boolean validateAccess( final URI uri, final HttpServletResponse response ) { if ( !AntPathMatcher.filter( includes, excludes, uri ) ) { logger.error( "Invalid credentials to path." ); try { response.sendError( SC_FORBIDDEN ); } catch ( Exception ex ) { logger.error( ex.getMessage() ); } return false; } return true; }
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 void testKeyFactory(ECPublicKey pub, ECPrivateKey priv) throws Exception { KeyFactory ecFact = KeyFactory.getInstance("ECDSA"); ECPublicKeySpec pubSpec = (ECPublicKeySpec)ecFact.getKeySpec(pub, ECPublicKeySpec.class); ECPrivateKeySpec privSpec = (ECPrivateKeySpec)ecFact.getKeySpec(priv, ECPrivateKeySpec.class); if (!pubSpec.getW().equals(pub.getW()) || !pubSpec.getParams().getCurve().equals(pub.getParams().getCurve())) { fail("pubSpec not correct"); } if (!privSpec.getS().equals(priv.getS()) || !privSpec.getParams().getCurve().equals(priv.getParams().getCurve())) { fail("privSpec not correct"); } ECPublicKey pubKey = (ECPublicKey)ecFact.translateKey(pub); ECPrivateKey privKey = (ECPrivateKey)ecFact.translateKey(priv); if (!pubKey.getW().equals(pub.getW()) || !pubKey.getParams().getCurve().equals(pub.getParams().getCurve())) { fail("pubKey not correct"); } if (!privKey.getS().equals(priv.getS()) || !privKey.getParams().getCurve().equals(priv.getParams().getCurve())) { fail("privKey not correct"); } }
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 Optional<Map<String, Object>> readPropertiesFromLoader(String fileName, String filePath, PropertySourceLoader propertySourceLoader) throws ConfigurationException { ResourceResolver resourceResolver = new ResourceResolver(); Optional<ResourceLoader> resourceLoader = resourceResolver.getSupportingLoader(filePath); ResourceLoader loader = resourceLoader.orElse(FileSystemResourceLoader.defaultLoader()); try { Optional<InputStream> inputStream = loader.getResourceAsStream(filePath); if (inputStream.isPresent()) { return Optional.of(propertySourceLoader.read(fileName, inputStream.get())); } else { throw new ConfigurationException("Failed to read configuration file: " + filePath); } } catch (IOException e) { throw new ConfigurationException("Unsupported properties file: " + fileName); } }
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 multipleValuesPerNameShouldBeAllowed() { final HttpHeadersBase headers = newEmptyHeaders(); headers.add("name", "value1"); headers.add("name", "value2"); headers.add("name", "value3"); assertThat(headers.size()).isEqualTo(3); final List<String> values = headers.getAll("name"); assertThat(values).hasSize(3) .containsExactly("value1", "value2", "value3"); }
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 displayVerificationWarningDialog(final Contact contact, final Invite invite) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.verify_omemo_keys); View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null); final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source); TextView warning = view.findViewById(R.id.warning); warning.setText(JidDialog.style(this, R.string.verifying_omemo_keys_trusted_source, contact.getJid().asBareJid().toEscapedString(), contact.getDisplayName())); builder.setView(view); builder.setPositiveButton(R.string.confirm, (dialog, which) -> { if (isTrustedSource.isChecked() && invite.hasFingerprints()) { xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints()); } switchToConversationDoNotAppend(contact, invite.getBody()); }); builder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish()); AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(false); dialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish()); dialog.show(); }
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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { UserFactory.init(); } catch (Throwable e) { throw new ServletException("AddNewUserServlet: Error initialising user factory." + e); } UserManager userFactory = UserFactory.getInstance(); String userID = request.getParameter("userID"); if (userID != null && userID.matches(".*[&<>\"`']+.*")) { throw new ServletException("User ID must not contain any HTML markup."); } String password = request.getParameter("pass1"); boolean hasUser = false; try { hasUser = userFactory.hasUser(userID); } catch (Throwable e) { throw new ServletException("can't determine if user " + userID + " already exists in users.xml.", e); } if (hasUser) { RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/userGroupView/users/newUser.jsp?action=redo"); dispatcher.forward(request, response); } else { final Password pass = new Password(); pass.setEncryptedPassword(UserFactory.getInstance().encryptedPassword(password, true)); pass.setSalt(true); final User newUser = new User(); newUser.setUserId(userID); newUser.setPassword(pass); final HttpSession userSession = request.getSession(false); userSession.setAttribute("user.modifyUser.jsp", newUser); // forward the request for proper display RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/userGroupView/users/modifyUser.jsp"); dispatcher.forward(request, response); } }
1
Java
CWE-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 setNeeded() { needed.on(); }
1
Java
NVD-CWE-noinfo
null
null
null
safe
private boolean isAdmin(String accountName) { if (this.adminFilter != null) { try { InitialDirContext context = initContext(); String searchString = adminFilter.replace(":login", accountName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls); if (results.hasMoreElements()) { results.nextElement(); if (results.hasMoreElements()) { LOGGER.warn("Matched multiple users for the accountName: " + accountName); return false; } return true; } } catch (NamingException e) { return false; } } 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 void translate(ServerChatPacket packet, GeyserSession session) { TextPacket textPacket = new TextPacket(); textPacket.setPlatformChatId(""); textPacket.setSourceName(""); textPacket.setXuid(session.getAuthData().getXboxUUID()); switch (packet.getType()) { case CHAT: textPacket.setType(TextPacket.Type.CHAT); break; case SYSTEM: textPacket.setType(TextPacket.Type.SYSTEM); break; case NOTIFICATION: textPacket.setType(TextPacket.Type.TIP); break; default: textPacket.setType(TextPacket.Type.RAW); break; } textPacket.setNeedsTranslation(false); textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale())); session.sendUpstreamPacket(textPacket); }
0
Java
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
private static void testInvalidHeaders0(String requestStr) { testInvalidHeaders0(Unpooled.copiedBuffer(requestStr, CharsetUtil.US_ASCII)); }
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
private void testHeaderNameEndsWithControlChar(int controlChar) { ByteBuf responseBuffer = Unpooled.buffer(); responseBuffer.writeCharSequence("HTTP/1.1 200 OK\r\n" + "Host: netty.io\r\n", CharsetUtil.US_ASCII); responseBuffer.writeCharSequence("Transfer-Encoding", CharsetUtil.US_ASCII); responseBuffer.writeByte(controlChar); responseBuffer.writeCharSequence(": chunked\r\n\r\n", CharsetUtil.US_ASCII); testInvalidHeaders0(responseBuffer); }
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 initWithCustomLogHandler() throws Exception { servlet = new AgentServlet(); config = createMock(ServletConfig.class); context = createMock(ServletContext.class); HttpTestUtil.prepareServletConfigMock(config, new String[]{ConfigKey.LOGHANDLER_CLASS.getKeyValue(), CustomLogHandler.class.getName()}); HttpTestUtil.prepareServletContextMock(context,null); expect(config.getServletContext()).andStubReturn(context); expect(config.getServletName()).andStubReturn("jolokia"); replay(config, context); servlet.init(config); servlet.destroy(); assertTrue(CustomLogHandler.infoCount > 0); }
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
default Optional<String> findFirst(CharSequence name) { return getFirst(name, String.class); }
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 Argument<CompletableFuture> argumentType() { return Argument.of(CompletableFuture.class); }
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
private void logError( Throwable e ) { logger.error( "Failed to upload 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
public void doFilter(ServletRequest srequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) srequest; filterChain.doFilter(new XssHttpServletRequestWrapper(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 testImportBadSignature() throws IOException, ImporterException { PKIUtility pki = mock(PKIUtility.class); Importer i = new Importer(null, null, null, null, null, null, null, pki, 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(); i.loadExport(owner, archive, co); }
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 AESGMAC() { super(new GMac(new GCMBlockCipher(new AESEngine()))); }
1
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
safe
public FilterRegistrationBean<XssFilter> croseSiteFilter(){ FilterRegistrationBean<XssFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new XssFilter()); registrationBean.addUrlPatterns("/*"); return registrationBean; }
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 JiffleRuntime getRuntimeInstance(Jiffle.RuntimeModel model) throws it.geosolutions.jaiext.jiffle.JiffleException { return createRuntimeInstance(model, getRuntimeBaseClass(model), false); }
0
Java
CWE-94
Improper Control of Generation of Code ('Code Injection')
The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
public OldECIESwithCipher(BlockCipher baseCipher, int ivLength) { super(new OldIESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(baseCipher)), ivLength); }
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 <T extends Result> T setResult(Class<T> resultClass) throws SQLException { try { if (isDebugEnabled()) { debugCode( "getSource(" + (resultClass != null ? resultClass.getSimpleName() + ".class" : "null") + ')'); } checkEditable(); if (resultClass == null || resultClass == DOMResult.class) { domResult = new DOMResult(); state = State.SET_CALLED; return (T) domResult; } else if (resultClass == SAXResult.class) { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(); Writer writer = setCharacterStreamImpl(); transformerHandler.setResult(new StreamResult(writer)); SAXResult saxResult = new SAXResult(transformerHandler); closable = writer; state = State.SET_CALLED; return (T) saxResult; } else if (resultClass == StAXResult.class) { XMLOutputFactory xof = XMLOutputFactory.newInstance(); Writer writer = setCharacterStreamImpl(); StAXResult staxResult = new StAXResult(xof.createXMLStreamWriter(writer)); closable = writer; state = State.SET_CALLED; return (T) staxResult; } else if (StreamResult.class.equals(resultClass)) { Writer writer = setCharacterStreamImpl(); StreamResult streamResult = new StreamResult(writer); closable = writer; state = State.SET_CALLED; return (T) streamResult; } throw unsupported(resultClass.getName()); } catch (Exception e) { throw logAndConvert(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 void switchToConversationAndQuote(Conversation conversation, String text) { switchToConversation(conversation, text, true, null, false, false); }
1
Java
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
safe
protected void deactivateConversationContext(HttpServletRequest request) { try { ConversationContext conversationContext = httpConversationContext(); if (conversationContext.isActive()) { // Only deactivate the context if one is already active, otherwise we get Exceptions if (conversationContext instanceof LazyHttpConversationContextImpl) { LazyHttpConversationContextImpl lazyConversationContext = (LazyHttpConversationContextImpl) conversationContext; if (!lazyConversationContext.isInitialized()) { // if this lazy conversation has not been touched yet, just deactivate it lazyConversationContext.deactivate(); return; } } boolean isTransient = conversationContext.getCurrentConversation().isTransient(); if (ConversationLogger.LOG.isTraceEnabled()) { if (isTransient) { ConversationLogger.LOG.cleaningUpTransientConversation(); } else { ConversationLogger.LOG.cleaningUpConversation(conversationContext.getCurrentConversation().getId()); } } conversationContext.invalidate(); conversationContext.deactivate(); if (isTransient) { conversationDestroyedEvent.fire(request); } } } catch (Exception e) { ServletLogger.LOG.unableToDeactivateContext(httpConversationContext(), request); 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
public static String[] tokenizeToStringArray( String str, String delimiters ) { if ( str == null ) { return null; } final StringTokenizer st = new StringTokenizer( str, delimiters ); final List<String> tokens = new ArrayList<String>(); while ( st.hasMoreTokens() ) { final String token = st.nextToken().trim(); if ( token.length() > 0 ) { tokens.add( token ); } } return tokens.toArray( new String[ tokens.size() ] ); }
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 URIDryConverter(URI base, Map<PackageID, Manifest> dependencyManifests, boolean isBuild) { super(base, dependencyManifests, isBuild); this.base = URI.create(base.toString() + "/modules/info/"); try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); proxy = getProxy(); } catch (NoSuchAlgorithmException | KeyManagementException e) { // ignore errors } }
0
Java
CWE-306
Missing Authentication for Critical Function
The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
void controlChars() { assertThat(PathAndQuery.parse("/\0")).isNull(); assertThat(PathAndQuery.parse("/a\nb")).isNull(); assertThat(PathAndQuery.parse("/a\u007fb")).isNull(); // Escaped assertThat(PathAndQuery.parse("/%00")).isNull(); assertThat(PathAndQuery.parse("/a%09b")).isNull(); assertThat(PathAndQuery.parse("/a%0ab")).isNull(); assertThat(PathAndQuery.parse("/a%0db")).isNull(); assertThat(PathAndQuery.parse("/a%7fb")).isNull(); // With query string assertThat(PathAndQuery.parse("/\0?c")).isNull(); assertThat(PathAndQuery.parse("/a\tb?c")).isNull(); assertThat(PathAndQuery.parse("/a\nb?c")).isNull(); assertThat(PathAndQuery.parse("/a\rb?c")).isNull(); assertThat(PathAndQuery.parse("/a\u007fb?c")).isNull(); // With query string with control chars assertThat(PathAndQuery.parse("/?\0")).isNull(); assertThat(PathAndQuery.parse("/?%00")).isNull(); assertThat(PathAndQuery.parse("/?a\u007fb")).isNull(); assertThat(PathAndQuery.parse("/?a%7Fb")).isNull(); // However, 0x0A, 0x0D, 0x09 should be accepted in a query string. assertThat(PathAndQuery.parse("/?a\tb").query()).isEqualTo("a%09b"); assertThat(PathAndQuery.parse("/?a\nb").query()).isEqualTo("a%0Ab"); assertThat(PathAndQuery.parse("/?a\rb").query()).isEqualTo("a%0Db"); assertThat(PathAndQuery.parse("/?a%09b").query()).isEqualTo("a%09b"); assertThat(PathAndQuery.parse("/?a%0Ab").query()).isEqualTo("a%0Ab"); assertThat(PathAndQuery.parse("/?a%0Db").query()).isEqualTo("a%0Db"); }
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 BourneShell( boolean isLoginShell ) { setUnconditionalQuoting( true ); setShellCommand( "/bin/sh" ); setArgumentQuoteDelimiter( '\'' ); setExecutableQuoteDelimiter( '\'' ); setSingleQuotedArgumentEscaped( true ); setSingleQuotedExecutableEscaped( false ); setQuotedExecutableEnabled( true ); setArgumentEscapePattern("'\\%s'"); if ( isLoginShell ) { addShellArg( "-l" ); } }
1
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
safe
public void encodeDeepBinaryJSONWithNullValue() throws JSONException { JSONObject data = new JSONObject("{a: \"b\", c: 4, e: {g: null}, h: null}"); data.put("h", new byte[9]); Packet<JSONObject> packet = new Packet<>(Parser.BINARY_EVENT); packet.data = data; packet.nsp = "/"; packet.id = 600; Helpers.testBin(packet); }
0
Java
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
vulnerable
public void headersWithSameNamesAndValuesShouldBeEquivalent() { final HttpHeadersBase headers1 = newEmptyHeaders(); headers1.add("name1", "value1"); headers1.add("name2", "value2"); headers1.add("name2", "value3"); final HttpHeadersBase headers2 = newEmptyHeaders(); headers2.add("name1", "value1"); headers2.add("name2", "value2"); headers2.add("name2", "value3"); assertThat(headers2).isEqualTo(headers1); assertThat(headers1).isEqualTo(headers2); assertThat(headers1).isEqualTo(headers1); assertThat(headers2).isEqualTo(headers2); assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode()); assertThat(headers1.hashCode()).isEqualTo(headers1.hashCode()); assertThat(headers2.hashCode()).isEqualTo(headers2.hashCode()); }
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 translate(NetworkStackLatencyPacket packet, GeyserSession session) { long pingId; // so apparently, as of 1.16.200 // PS4 divides the network stack latency timestamp FOR US!!! // WTF if (session.getClientData().getDeviceOs().equals(DeviceOs.PS4)) { pingId = packet.getTimestamp(); } else { pingId = packet.getTimestamp() / 1000; } // negative timestamps are used as hack to fix the url image loading bug if (packet.getTimestamp() > 0) { if (session.getConnector().getConfig().isForwardPlayerPing()) { ClientKeepAlivePacket keepAlivePacket = new ClientKeepAlivePacket(pingId); session.sendDownstreamPacket(keepAlivePacket); } return; } // Hack to fix the url image loading bug UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket(); attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId()); AttributeData attribute = session.getPlayerEntity().getAttributes().get(GeyserAttributeType.EXPERIENCE_LEVEL); if (attribute != null) { attributesPacket.setAttributes(Collections.singletonList(attribute)); } else { attributesPacket.setAttributes(Collections.singletonList(GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(0))); } session.getConnector().getGeneralThreadPool().schedule( () -> session.sendUpstreamPacket(attributesPacket), 500, TimeUnit.MILLISECONDS); }
0
Java
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
private String encryptOld(String str) throws Exception { Cipher cipher = Secret.getCipher("AES"); cipher.init(Cipher.ENCRYPT_MODE, Util.toAes128Key(TEST_KEY)); return new String(Base64.encode(cipher.doFinal((str + "::::MAGIC::::").getBytes("UTF-8")))); }
1
Java
NVD-CWE-noinfo
null
null
null
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-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
safe
public void toScientificString(StringBuilder result) { assert(!isApproximate); if (isNegative()) { result.append('-'); } if (precision == 0) { result.append("0E+0"); return; } // NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from // rOptPos (aka -maxFrac) due to overflow. int upperPos = Math.min(precision + scale, lOptPos) - scale - 1; int lowerPos = Math.max(scale, rOptPos) - scale; int p = upperPos; result.append((char) ('0' + getDigitPos(p))); if ((--p) >= lowerPos) { result.append('.'); for (; p >= lowerPos; p--) { result.append((char) ('0' + getDigitPos(p))); } } result.append('E'); int _scale = upperPos + scale; if (_scale < 0) { _scale *= -1; result.append('-'); } else { result.append('+'); } if (_scale == 0) { result.append('0'); } int insertIndex = result.length(); while (_scale > 0) { int quot = _scale / 10; int rem = _scale % 10; result.insert(insertIndex, (char) ('0' + rem)); _scale = quot; } }
0
Java
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
vulnerable
private BigInteger validate(BigInteger y, DHParameters dhParams) { if (y == null) { throw new NullPointerException("y value cannot be null"); } if (dhParams.getQ() != null) { if (ONE.equals(y.modPow(dhParams.getQ(), dhParams.getP()))) { return y; } throw new IllegalArgumentException("Y value does not appear to be in correct group"); } else { // TLS check if (y.compareTo(TWO) < 0 || y.compareTo(dhParams.getP().subtract(TWO)) > 0) { throw new IllegalArgumentException("invalid DH public key"); } return y; // we can't validate without Q. } }
1
Java
CWE-320
Key Management Errors
Weaknesses in this category are related to errors in the management of cryptographic keys.
https://cwe.mitre.org/data/definitions/320.html
safe
protected void connectInternal() throws SmackException, IOException, XMPPException { // Establishes the TCP connection to the server and does setup the reader and writer. Throws an exception if // there is an error establishing the connection connectUsingConfiguration(); // We connected successfully to the servers TCP port socketClosed = false; initConnection(); // Wait with SASL auth until the SASL mechanisms have been received saslFeatureReceived.checkIfSuccessOrWaitOrThrow(); // If TLS is required but the server doesn't offer it, disconnect // from the server and throw an error. First check if we've already negotiated TLS // and are secure, however (features get parsed a second time after TLS is established). if (!isSecureConnection() && getConfiguration().getSecurityMode() == SecurityMode.required) { shutdown(); throw new SecurityRequiredByClientException(); } // Make note of the fact that we're now connected. connected = true; callConnectionConnectedListener(); // Automatically makes the login if the user was previously connected successfully // to the server and the connection was terminated abruptly if (wasAuthenticated) { login(); notifyReconnection(); } }
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 logError(Throwable e) { logger.error("Failed to upload a file.", e); }
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 ConstraintValidatorContext getContext() { return constraintValidatorContext; }
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 static String encodePathToPercents(Bytes value) { if (!value.hasEncodedBytes()) { // Deprecated, but it fits perfect for our use case. // noinspection deprecation return new String(value.data, 0, 0, value.length); } // Slow path: some percent-encoded chars. return slowEncodePathToPercents(value); }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
public boolean verify(String token) { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)) .withIssuer(ISSUER) .build(); try { verifier.verify(token); return true; } catch (JWTVerificationException e) { log.warn("verify jwt token failed " + e.getMessage()); 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 boolean processStyleTag(Element ele, Node parentNode) { /* * Invoke the css parser on this element. */ CssScanner styleScanner = new CssScanner(policy, messages, policy.isEmbedStyleSheets()); try { Node firstChild = ele.getFirstChild(); if (firstChild != null) { String toScan = firstChild.getNodeValue(); CleanResults cr = styleScanner.scanStyleSheet(toScan, policy.getMaxInputSize()); errorMessages.addAll(cr.getErrorMessages()); /* * If IE gets an empty style tag, i.e. <style/> it will * break all CSS on the page. I wish I was kidding. So, * if after validation no CSS properties are left, we * would normally be left with an empty style tag and * break all CSS. To prevent that, we have this check. */ final String cleanHTML = cr.getCleanHTML(); if (cleanHTML == null || cleanHTML.equals("")) { firstChild.setNodeValue("/* */"); } else { firstChild.setNodeValue(cleanHTML); } } } catch (DOMException | ScanException | ParseException | NumberFormatException e) { /* * ParseException shouldn't be possible anymore, but we'll leave it * here because I (Arshan) am hilariously dumb sometimes. * Batik can throw NumberFormatExceptions (see bug #48). */ addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(ele.getFirstChild().getNodeValue())}); parentNode.removeChild(ele); return true; } return false; }
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 DefaultHttp2ConnectionDecoder(Http2Connection connection, Http2ConnectionEncoder encoder, Http2FrameReader frameReader, Http2PromisedRequestVerifier requestVerifier, boolean autoAckSettings, boolean autoAckPing) { this.autoAckPing = autoAckPing; if (autoAckSettings) { settingsReceivedConsumer = null; } else { if (!(encoder instanceof Http2SettingsReceivedConsumer)) { throw new IllegalArgumentException("disabling autoAckSettings requires the encoder to be a " + Http2SettingsReceivedConsumer.class); } settingsReceivedConsumer = (Http2SettingsReceivedConsumer) encoder; } this.connection = checkNotNull(connection, "connection"); contentLengthKey = this.connection.newKey(); this.frameReader = checkNotNull(frameReader, "frameReader"); this.encoder = checkNotNull(encoder, "encoder"); this.requestVerifier = checkNotNull(requestVerifier, "requestVerifier"); if (connection.local().flowController() == null) { connection.local().flowController(new DefaultHttp2LocalFlowController(connection)); } connection.local().flowController().frameWriter(encoder.frameWriter()); }
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
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, null); 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()); } switchToConversation(contact, invite == null ? null : invite.getBody()); return true; } }); dialog.show(ft, FRAGMENT_TAG_DIALOG); }
0
Java
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
private void testBSI() throws Exception { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ECDSA", "BC"); kpGen.initialize(new ECGenParameterSpec(TeleTrusTObjectIdentifiers.brainpoolP512r1.getId())); KeyPair kp = kpGen.generateKeyPair(); byte[] data = "Hello World!!!".getBytes(); String[] cvcAlgs = {"SHA1WITHCVC-ECDSA", "SHA224WITHCVC-ECDSA", "SHA256WITHCVC-ECDSA", "SHA384WITHCVC-ECDSA", "SHA512WITHCVC-ECDSA"}; String[] cvcOids = {EACObjectIdentifiers.id_TA_ECDSA_SHA_1.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_224.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_256.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_384.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_512.getId()}; testBsiAlgorithms(kp, data, cvcAlgs, cvcOids); String[] plainAlgs = {"SHA1WITHPLAIN-ECDSA", "SHA224WITHPLAIN-ECDSA", "SHA256WITHPLAIN-ECDSA", "SHA384WITHPLAIN-ECDSA", "SHA512WITHPLAIN-ECDSA", "RIPEMD160WITHPLAIN-ECDSA"}; String[] plainOids = {BSIObjectIdentifiers.ecdsa_plain_SHA1.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA224.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA256.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA384.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA512.getId(), BSIObjectIdentifiers.ecdsa_plain_RIPEMD160.getId()}; testBsiAlgorithms(kp, data, plainAlgs, plainOids); }
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 translate(ServerSetActionBarTextPacket packet, GeyserSession session) { String text; if (packet.getText() == null) { //TODO 1.17 can this happen? text = " "; } else { text = MessageTranslator.convertMessage(packet.getText(), session.getLocale()); } SetTitlePacket titlePacket = new SetTitlePacket(); titlePacket.setType(SetTitlePacket.Type.ACTIONBAR); titlePacket.setText(text); 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
private ServletFileUpload getServletFileUpload() { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload( factory ); upload.setHeaderEncoding( "UTF-8" ); return upload; }
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 IESwithAES() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(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
void multipleValuesPerNameIteratorEmpty() { final HttpHeadersBase headers = newEmptyHeaders(); assertThat(headers.valueIterator("name")).isExhausted(); assertThatThrownBy(() -> headers.valueIterator("name").next()) .isInstanceOf(NoSuchElementException.class); }
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 IBaseResource addCommonParams(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) { final String serverId = theRequest.getServerIdWithDefault(myConfig); final String serverBase = theRequest.getServerBase(theServletRequest, myConfig); final String serverName = theRequest.getServerName(myConfig); final String apiKey = theRequest.getApiKey(theServletRequest, myConfig); theModel.put("serverId", serverId); theModel.put("base", serverBase); theModel.put("baseName", serverName); theModel.put("apiKey", apiKey); theModel.put("resourceName", defaultString(theRequest.getResource())); theModel.put("encoding", theRequest.getEncoding()); theModel.put("pretty", theRequest.getPretty()); theModel.put("_summary", theRequest.get_summary()); theModel.put("serverEntries", myConfig.getIdToServerName()); return loadAndAddConf(theServletRequest, theRequest, theModel); }
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
private NameID parseNameId(NameIDType element) { NameID nameId = new NameID(); nameId.format = NameIDFormat.fromSAMLFormat(element.getFormat()); nameId.id = element.getValue(); return nameId; }
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 test_like_startsWith() { Entity from = from(Entity.class); where(from.getCode()).like().startsWith("test"); Query<Entity> select = select(from); assertEquals("select entity_0 from Entity entity_0 where entity_0.code like 'test%'", select.getQuery()); }
0
Java
NVD-CWE-noinfo
null
null
null
vulnerable
public void testHeaderNameEndsWithControlChar0c() { testHeaderNameEndsWithControlChar(0x0c); }
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
private static File newFile() throws IOException { File file = File.createTempFile("netty-", ".tmp"); file.deleteOnExit(); final FileOutputStream out = new FileOutputStream(file); out.write(data); out.close(); return file; }
0
Java
CWE-379
Creation of Temporary File in Directory with Insecure Permissions
The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file.
https://cwe.mitre.org/data/definitions/379.html
vulnerable
public void after() { Secret.resetKeyForTest(); }
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 ExitCode runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException { if (saveFilename != null && loadFilename != null) { params.getConsole().printErrorText("Can't use both --load and --save"); return ExitCode.COMMANDLINE_ERROR; } if (saveFilename != null) { invalidateChanges(params); RemoteDaemonicParserState state = params.getParser().storeParserState(params.getCell()); try (FileOutputStream fos = new FileOutputStream(saveFilename); ZipOutputStream zipos = new ZipOutputStream(fos)) { zipos.putNextEntry(new ZipEntry("parser_data")); try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) { oos.writeObject(state); } } } else if (loadFilename != null) { try (FileInputStream fis = new FileInputStream(loadFilename); ZipInputStream zipis = new ZipInputStream(fis)) { ZipEntry entry = zipis.getNextEntry(); Preconditions.checkState(entry.getName().equals("parser_data")); try (ObjectInputStream ois = new ObjectInputStream(zipis)) { RemoteDaemonicParserState state; try { state = (RemoteDaemonicParserState) ois.readObject(); } catch (ClassNotFoundException e) { params.getConsole().printErrorText("Invalid file format"); return ExitCode.COMMANDLINE_ERROR; } params.getParser().restoreParserState(state, params.getCell()); } } invalidateChanges(params); ParserConfig configView = params.getBuckConfig().getView(ParserConfig.class); if (configView.isParserCacheMutationWarningEnabled()) { params .getConsole() .printErrorText( params .getConsole() .getAnsi() .asWarningText( "WARNING: Buck injected a parser state that may not match the local state.")); } } return ExitCode.SUCCESS; }
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
protected void onStart() { super.onStart(); Intent intent = getIntent(); intent.putExtra( SettingsActivity.SP_FEED_LIST_LAYOUT, mPrefs.getString(SettingsActivity.SP_FEED_LIST_LAYOUT, "0") ); setResult(RESULT_OK,intent); }
0
Java
CWE-829
Inclusion of Functionality from Untrusted Control Sphere
The software imports, requires, or includes executable functionality (such as a library) from a source that is outside of the intended control sphere.
https://cwe.mitre.org/data/definitions/829.html
vulnerable
public void testHttpServerResponseHeadersDontContainCROrLF() throws Exception { server.requestHandler(req -> { List<BiConsumer<String, String>> list = Arrays.asList( req.response()::putHeader, req.response().headers()::set, req.response().headers()::add ); list.forEach(cs -> { try { cs.accept("header-name: header-value\r\nanother-header", "another-value"); fail(); } catch (IllegalArgumentException e) { } }); assertEquals(Collections.emptySet(), req.response().headers().names()); req.response().end(); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.headers().forEach(header -> { String name = header.getKey(); switch (name.toLowerCase()) { case ":status": case "content-length": break; default: fail("Unexpected header " + name); } }); testComplete(); }); await(); }
1
Java
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
CreateCommentResponse saveComment() { CreateCommentRequest createCommentRequest = ZrLogUtil.convertRequestParam(getRequest().getParameterMap(), CreateCommentRequest.class); createCommentRequest.setIp(WebTools.getRealIp(getRequest())); createCommentRequest.setUserAgent(getHeader("User-Agent")); return commentService.save(createCommentRequest); }
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
protected XMLReader installXMLFilter(XMLReader reader) { XMLFilter filter = getXMLFilter(); if (filter != null) { // find the root XMLFilter XMLFilter root = filter; while (true) { XMLReader parent = root.getParent(); if (parent instanceof XMLFilter) { root = (XMLFilter) parent; } else { break; } } root.setParent(reader); return filter; } return reader; }
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 pseudoHeaderNameValidation() { // Known pseudo header names should pass validation. assertThat((Object) HttpHeaderNames.of(":method")).isSameAs(HttpHeaderNames.METHOD); assertThat((Object) HttpHeaderNames.of(":scheme")).isSameAs(HttpHeaderNames.SCHEME); assertThat((Object) HttpHeaderNames.of(":authority")).isSameAs(HttpHeaderNames.AUTHORITY); assertThat((Object) HttpHeaderNames.of(":path")).isSameAs(HttpHeaderNames.PATH); assertThat((Object) HttpHeaderNames.of(":status")).isSameAs(HttpHeaderNames.STATUS); // However, any other headers that start with `:` should fail. assertThatThrownBy(() -> HttpHeaderNames.of(":foo")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("malformed header name: :foo"); }
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 static void validateValue(String value) { final int valueLength = value.length(); for (int i = 0; i < valueLength; i++) { final char ch = value.charAt(i); if ((ch & PROHIBITED_VALUE_CHAR_MASK) != 0) { // ch >= 16 continue; } // ch < 16 if (PROHIBITED_VALUE_CHARS.get(ch)) { throw new IllegalArgumentException(malformedHeaderValueMessage(value)); } } }
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 SAXReader(String xmlReaderClassName) throws SAXException { if (xmlReaderClassName != null) { this.xmlReader = XMLReaderFactory .createXMLReader(xmlReaderClassName); } }
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 testValidGroupIds() { testInvalidGroupId("John-Doe",false); testInvalidGroupId("Jane/Doe",false); testInvalidGroupId("John.Doe",false); testInvalidGroupId("Jane#Doe", false); testInvalidGroupId("John@Döe.com", false); testInvalidGroupId("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 setDocumentFactory(DocumentFactory documentFactory) { this.factory = documentFactory; }
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 String getPath(String test, int sequence, boolean poison) { String path = contextPath + "/servlet?action=" + test + "&sequence=" + sequence; if (poison) { path += "&poison=true"; } return path; }
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 synchronized <T extends Source> T getSource(Class<T> sourceClass) throws SQLException { checkFreed(); ensureInitialized(); if (data == null) { return null; } try { if (sourceClass == null || DOMSource.class.equals(sourceClass)) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new NonPrintingErrorHandler()); InputSource input = new InputSource(new StringReader(data)); return (T) new DOMSource(builder.parse(input)); } else if (SAXSource.class.equals(sourceClass)) { InputSource is = new InputSource(new StringReader(data)); return (T) new SAXSource(is); } else if (StreamSource.class.equals(sourceClass)) { return (T) new StreamSource(new StringReader(data)); } else if (StAXSource.class.equals(sourceClass)) { XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(data)); return (T) new StAXSource(xsr); } } catch (Exception e) { throw new PSQLException(GT.tr("Unable to decode xml data."), PSQLState.DATA_ERROR, e); } throw new PSQLException(GT.tr("Unknown XML Source class: {0}", sourceClass), 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
public void existingDocumentFromUITemplateProviderSpecifiedNonTerminalOverridenFromUIToTerminal() throws Exception { // current document = xwiki:Main.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(false); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider String templateProviderFullName = "XWiki.MyTemplateProvider"; String spaceReferenceString = "X"; when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString); when(mockRequest.getParameter("name")).thenReturn("Y"); when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName); when(mockRequest.getParameter("tocreate")).thenReturn("terminal"); // Mock 1 existing template provider that creates terminal documents. mockExistingTemplateProviders(templateProviderFullName, new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, false); // 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, even if the template provider says otherwise. // Also 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 void serviceAccount() { Response response = realm.clients().create(ClientBuilder.create().clientId("serviceClient").serviceAccount().build()); String id = ApiUtil.getCreatedId(response); getCleanup().addClientUuid(id); response.close(); UserRepresentation userRep = realm.clients().get(id).getServiceAccountUser(); assertEquals("service-account-serviceclient", userRep.getUsername()); // KEYCLOAK-11197 service accounts are no longer created with a placeholder e-mail. assertNull(userRep.getEmail()); }
1
Java
CWE-798
Use of Hard-coded Credentials
The software contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data.
https://cwe.mitre.org/data/definitions/798.html
safe
public Template getTemplate( String templateId, String templateContent, String errorTemplateId, String errorTemplateContent, TemplateContextType templateContextType) { if (templateContextType.equals(TemplateContextType.EMPTY)) { return new FreeMarkerTemplate( templateId, templateContent, errorTemplateId, errorTemplateContent, null, _configuration, _templateContextHelper, _stringTemplateLoader); } else if (templateContextType.equals(TemplateContextType.RESTRICTED)) { return new RestrictedTemplate( new FreeMarkerTemplate( templateId, templateContent, errorTemplateId, errorTemplateContent, _restrictedHelperUtilities, _configuration, _templateContextHelper, _stringTemplateLoader), _templateContextHelper.getRestrictedVariables()); } else if (templateContextType.equals(TemplateContextType.STANDARD)) { return new FreeMarkerTemplate( templateId, templateContent, errorTemplateId, errorTemplateContent, _standardHelperUtilities, _configuration, _templateContextHelper, _stringTemplateLoader); } return null; }
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 testWhitespaceInTransferEncoding02() { String requestStr = "POST / HTTP/1.1" + "Transfer-Encoding : chunked\r\n" + "Host: target.com" + "Content-Length: 65\r\n\r\n" + "0\r\n\r\n" + "GET /maliciousRequest HTTP/1.1\r\n" + "Host: evilServer.com\r\n" + "Foo: x"; testInvalidHeaders0(requestStr); }
1
Java
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
public int doFinal(byte[] out, int outOff) throws DataLengthException, IllegalStateException { try { return ccm.doFinal(out, 0); } catch (InvalidCipherTextException e) { throw new IllegalStateException("exception on doFinal(): " + e.toString()); } }
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
void dotsAndEqualsInNameValueQuery() { QUERY_SEPARATORS.forEach(qs -> { final PathAndQuery res = parse("/?a=..=" + qs + "b=..="); assertThat(res).isNotNull(); assertThat(res.query()).isEqualTo("a=..=" + qs + "b=..="); assertThat(QueryParams.fromQueryString(res.query(), true)).containsExactly( Maps.immutableEntry("a", "..="), Maps.immutableEntry("b", "..=") ); final PathAndQuery res2 = parse("/?a==.." + qs + "b==.."); assertThat(res2).isNotNull(); assertThat(res2.query()).isEqualTo("a==.." + qs + "b==.."); assertThat(QueryParams.fromQueryString(res2.query(), true)).containsExactly( Maps.immutableEntry("a", "=.."), Maps.immutableEntry("b", "=..") ); final PathAndQuery res3 = parse("/?a==..=" + qs + "b==..="); assertThat(res3).isNotNull(); assertThat(res3.query()).isEqualTo("a==..=" + qs + "b==..="); assertThat(QueryParams.fromQueryString(res3.query(), true)).containsExactly( Maps.immutableEntry("a", "=..="), Maps.immutableEntry("b", "=..=") ); }); }
1
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep() { Shell sh = newShell(); sh.setWorkingDirectory( "\\usr\\local\\'something else'" ); sh.setExecutable( "chmod" ); String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " ); assertEquals( "/bin/sh -c cd \"\\usr\\local\\\'something else\'\" && chmod", executable ); }
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 canReadPreSec304Secrets() throws Exception { FreeStyleProject project = j.jenkins.getItemByFullName("OldSecret", FreeStyleProject.class); String oldxml = project.getConfigFile().asString(); //It should be unchanged on disk assertThat(oldxml, containsString("<defaultValue>z/Dd3qrHdQ6/C5lR7uEafM/jD3nQDrGprw3XsfZ/0vo=</defaultValue>")); ParametersDefinitionProperty property = project.getProperty(ParametersDefinitionProperty.class); ParameterDefinition definition = property.getParameterDefinitions().get(0); assertTrue(definition instanceof PasswordParameterDefinition); Secret secret = ((PasswordParameterDefinition) definition).getDefaultValueAsSecret(); assertEquals("theSecret", secret.getPlainText()); //OK it was read correctly from disk, now the first roundtrip should update the encrypted value project = j.configRoundtrip(project); String newXml = project.getConfigFile().asString(); assertNotEquals(oldxml, newXml); //This could have changed because Jenkins has moved on, so not really a good check assertThat(newXml, not(containsString("<defaultValue>z/Dd3qrHdQ6/C5lR7uEafM/jD3nQDrGprw3XsfZ/0vo=</defaultValue>"))); Pattern p = Pattern.compile("<defaultValue>\\{[A-Za-z0-9+/]+={0,2}}</defaultValue>"); assertTrue(p.matcher(newXml).find()); //But the next roundtrip should result in the same data project = j.configRoundtrip(project); String round2 = project.getConfigFile().asString(); assertEquals(newXml, round2); }
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 Document read(Reader reader) throws DocumentException { InputSource source = new InputSource(reader); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); }
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(CharSequence name) { if (name instanceof AsciiString) { return of((AsciiString) name); } final String lowerCased = Ascii.toLowerCase(requireNonNull(name, "name")); final AsciiString cached = map.get(lowerCased); return cached != null ? cached : AsciiString.cached(lowerCased); }
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 translate(ServerUnlockRecipesPacket packet, GeyserSession session) { if (packet.getAction() == UnlockRecipesAction.REMOVE) { session.getUnlockedRecipes().removeAll(Arrays.asList(packet.getRecipes())); } else { session.getUnlockedRecipes().addAll(Arrays.asList(packet.getRecipes())); } }
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 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
private String doResolveSqlDriverNameFromJar(File driverFile) { JarFile jarFile = null; try { jarFile = new JarFile(driverFile); } catch (IOException e) { log.error("resolve driver class name error", e); throw DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR.exception(e.getMessage()); } final JarFile driverJar = jarFile; String driverClassName = jarFile.stream() .filter(entry -> entry.getName().contains("META-INF/services/java.sql.Driver")) .findFirst() .map(entry -> { InputStream stream = null; BufferedReader reader = null; try { stream = driverJar.getInputStream(entry); reader = new BufferedReader(new InputStreamReader(stream)); return reader.readLine(); } catch (IOException e) { log.error("resolve driver class name error", e); throw DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR.exception(e.getMessage()); } finally { IOUtils.closeQuietly(reader, ex -> log.error("close reader error", ex)); } }) .orElseThrow(DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR::exception); IOUtils.closeQuietly(jarFile, ex -> log.error("close jar file error", ex)); return driverClassName; }
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 newDocumentButNonTerminalFromURL() throws Exception { // new document = xwiki:X.Y DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X"), "Y"); 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=nonterminal request parameter when(mockRequest.getParameter("tocreate")).thenReturn("nonterminal"); // 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); verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki", context); }
0
Java
CWE-862
Missing Authorization
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
vulnerable
public void testHeaderNameStartsWithControlChar0c() { testHeaderNameStartsWithControlChar(0x0c); }
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
TEST(ProtocolSkipTest, SkipStop) { IOBufQueue queue; CompactProtocolWriter writer; writer.setOutput(&queue); writer.writeFieldStop(); auto buf = queue.move(); CompactProtocolReader reader; reader.setInput(buf.get()); bool thrown = false; try { reader.skip(TType::T_STOP); } catch (const TProtocolException& ex) { EXPECT_EQ(TProtocolException::INVALID_DATA, ex.getType()); thrown = true; } EXPECT_TRUE(thrown); }
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
public void createElementAmpersand() { DocumentHelper.createElement("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
public void corsStrictCheckingOff() { InputStream is = getClass().getResourceAsStream("/allow-origin1.xml"); PolicyRestrictor restrictor = new PolicyRestrictor(is); // Allways true since we want a strict check but strict checking is off. assertTrue(restrictor.isOriginAllowed("http://bla.com", true)); assertTrue(restrictor.isOriginAllowed("http://www.jolokia.org", true)); assertTrue(restrictor.isOriginAllowed("https://www.consol.de", 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
private SecretKey getKey() { try { if (secret==null) { synchronized (this) { if (secret==null) { byte[] payload = load(); if (payload==null) { payload = ConfidentialStore.get().randomBytes(256); store(payload); } // Due to the stupid US export restriction JDK only ships 128bit version. secret = new SecretKeySpec(payload,0,128/8, ALGORITHM); } } } return secret; } catch (IOException e) { throw new Error("Failed to load the key: "+getId(),e); } }
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
public SecretKey deriveKey(final SecretKey sharedSecret, final int keyLengthBits, final byte[] otherInfo) throws JOSEException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); final MessageDigest md = getMessageDigest(); for (int i=1; i <= computeDigestCycles(ByteUtils.safeBitLength(md.getDigestLength()), keyLengthBits); i++) { byte[] counterBytes = IntegerUtils.toBytes(i); md.update(counterBytes); md.update(sharedSecret.getEncoded()); if (otherInfo != null) { md.update(otherInfo); } try { baos.write(md.digest()); } catch (IOException e) { throw new JOSEException("Couldn't write derived key: " + e.getMessage(), e); } } byte[] derivedKeyMaterial = baos.toByteArray(); final int keyLengthBytes = ByteUtils.byteLength(keyLengthBits); if (derivedKeyMaterial.length == keyLengthBytes) { // Return immediately return new SecretKeySpec(derivedKeyMaterial, "AES"); } return new SecretKeySpec(ByteUtils.subArray(derivedKeyMaterial, 0, keyLengthBytes), "AES"); }
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 boolean canSerialize(Throwable t) { try { serialize(t); return true; } catch (Throwable throwable) { return false; } }
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 headerSignContentLengthValidationShouldPropagateWithEndStream(boolean minus, boolean endStream) { LastInboundHandler inboundHandler = new LastInboundHandler(); request.add(HttpHeaderNames.CONTENT_LENGTH, (minus ? "-" : "+") + 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
public SAXReader(String xmlReaderClassName, boolean validating) throws SAXException { if (xmlReaderClassName != null) { this.xmlReader = XMLReaderFactory .createXMLReader(xmlReaderClassName); } 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 testSquare() { int COUNT = 1000; for (int i = 0; i < COUNT; ++i) { ECFieldElement x = generateMultiplyInput_Random(); BigInteger X = x.toBigInteger(); BigInteger R = X.multiply(X).mod(Q); ECFieldElement z = x.square(); BigInteger Z = z.toBigInteger(); assertEquals(R, Z); } }
1
Java
CWE-19
Data Processing Errors
Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information.
https://cwe.mitre.org/data/definitions/19.html
safe
public 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","strict-checking"); if (node.getNodeName().equals("allow-origin")) { String p = node.getTextContent().trim().toLowerCase(); p = Pattern.quote(p).replace("*", "\\E.*\\Q"); patterns.add(Pattern.compile("^" + p + "$")); } else if (node.getNodeName().equals("strict-checking")) { strictChecking = 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