code
stringlengths
12
2.05k
label
int64
0
1
programming_language
stringclasses
9 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
103
description
stringlengths
36
1.23k
url
stringlengths
36
48
label_name
stringclasses
2 values
public UPathHand(UPath source, Random rnd) { final UPath result = new UPath(); Point2D last = new Point2D.Double(); for (USegment segment : source) { final USegmentType type = segment.getSegmentType(); if (type == USegmentType.SEG_MOVETO) { final double x = segment.getCoord()[0]; final double y = segment.getCoord()[1]; result.moveTo(x, y); last = new Point2D.Double(x, y); } else if (type == USegmentType.SEG_CUBICTO) { final double x2 = segment.getCoord()[4]; final double y2 = segment.getCoord()[5]; final HandJiggle jiggle = HandJiggle.create(last, 2.0, rnd); final CubicCurve2D tmp = new CubicCurve2D.Double(last.getX(), last.getY(), segment.getCoord()[0], segment.getCoord()[1], segment.getCoord()[2], segment.getCoord()[3], x2, y2); jiggle.curveTo(tmp); jiggle.appendTo(result); last = new Point2D.Double(x2, y2); } else if (type == USegmentType.SEG_LINETO) { final double x = segment.getCoord()[0]; final double y = segment.getCoord()[1]; final HandJiggle jiggle = new HandJiggle(last.getX(), last.getY(), defaultVariation, rnd); jiggle.lineTo(x, y); for (USegment seg2 : jiggle.toUPath()) { if (seg2.getSegmentType() == USegmentType.SEG_LINETO) { result.lineTo(seg2.getCoord()[0], seg2.getCoord()[1]); } } last = new Point2D.Double(x, y); } else { this.path = source; return; } } this.path = result; this.path.setDeltaShadow(source.getDeltaShadow()); }
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
private static boolean isBase64(String s) { for (int i=0; i<s.length(); i++) if (!isBase64(s.charAt(i))) return false; return true; }
1
Java
NVD-CWE-noinfo
null
null
null
safe
public List<Entry<P>> getPrimitive(final byte[] identifier) { List<Entry<P>> found = primitives.get(new String(identifier, UTF_8)); return found != null ? found : Collections.<Entry<P>>emptyList(); }
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 void setStripWhitespaceText(boolean stripWhitespaceText) { this.stripWhitespaceText = stripWhitespaceText; }
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 testWrapMemoryMapped() throws Exception { File file = PlatformDependent.createTempFile("netty-test", "tmp", null); FileChannel output = null; FileChannel input = null; ByteBuf b1 = null; ByteBuf b2 = null; try { output = new RandomAccessFile(file, "rw").getChannel(); byte[] bytes = new byte[1024]; PlatformDependent.threadLocalRandom().nextBytes(bytes); output.write(ByteBuffer.wrap(bytes)); input = new RandomAccessFile(file, "r").getChannel(); ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size()); b1 = buffer(m); ByteBuffer dup = m.duplicate(); dup.position(2); dup.limit(4); b2 = buffer(dup); Assert.assertEquals(b2, b1.slice(2, 2)); } finally { if (b1 != null) { b1.release(); } if (b2 != null) { b2.release(); } if (output != null) { output.close(); } if (input != null) { input.close(); } file.delete(); } }
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 RedirectView callback(@RequestParam(defaultValue = "/") String redirect, @PathVariable String serverId, @RequestParam String code, @RequestParam String state, HttpServletRequest request, HttpSession session) throws UnsupportedEncodingException { try { String cachedState = (String) session.getAttribute(STATE_SESSION_KEY); // if (!state.equals(cachedState)) throw new BusinessException("state error"); oAuth2RequestService.doEvent(serverId, new OAuth2CodeAuthBeforeEvent(code, state, request::getParameter)); return new RedirectView(URLDecoder.decode(redirect, "UTF-8")); } finally { session.removeAttribute(STATE_SESSION_KEY); } }
0
Java
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
vulnerable
public 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); }
0
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
public void newDocumentFromURLTemplateProviderSpecifiedNonTerminal() throws Exception { // new document = xwiki:X.Y DocumentReference documentReference = new DocumentReference("xwiki", "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); // 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, 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 and using a template, as specified in the template // provider. verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context); }
0
Java
CWE-862
Missing Authorization
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
vulnerable
public void write(byte[] b, int offset, int length) throws IOException { if (b == null) { throw new NullPointerException(); } if (offset < 0 || offset + length > b.length) { throw new ArrayIndexOutOfBoundsException(); } write(fd, b, offset, length); }
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
public static void setup() throws IOException { path = CommonIOServiceDotFileTest.createTempDirectory(); System.setProperty( "org.uberfire.nio.git.dir", path.getAbsolutePath() ); System.out.println( ".niogit: " + path.getAbsolutePath() ); final URI newRepo = URI.create( "git://antpathmatcher" ); ioService.newFileSystem( newRepo, new HashMap<String, Object>() ); }
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 synchronized int rewriteRecursive(File dir, TaskListener listener) throws InvalidKeyException { return rewriteRecursive(dir,"",listener); }
1
Java
NVD-CWE-noinfo
null
null
null
safe
final void add(CharSequence name, String value) { final AsciiString normalizedName = normalizeName(name); requireNonNull(value, "value"); final int h = normalizedName.hashCode(); final int i = index(h); add0(h, i, normalizedName, value); }
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
protected void runTeardown() { Assert.assertTrue("Error during initialization", messagedInitialization); Assert.assertTrue("Socket connection is not allowed", securityExceptionOccurred); }
1
Java
CWE-862
Missing Authorization
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { if (arguments.isEmpty()) { throw new TemplateModelException( "This method must have at least one argument as the name of " + "the class to instantiate"); } Class<?> clazz = null; try { String className = String.valueOf(arguments.get(0)); clazz = Class.forName( className, true, PACLClassLoaderUtil.getContextClassLoader()); } catch (Exception e) { throw new TemplateModelException(e.getMessage()); } BeansWrapper beansWrapper = BeansWrapper.getDefaultInstance(); Object object = beansWrapper.newInstance( clazz, arguments.subList(1, arguments.size())); return beansWrapper.wrap(object); }
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 accessAllowed() { expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true); replay(backend); handler.checkAccess("localhost", "127.0.0.1",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 dataContentLengthMissmatch() throws Exception { dataContentLengthInvalid(false); }
1
Java
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
private static String slowEncodeQueryToPercents(Bytes value) { final int length = value.length; final StringBuilder buf = new StringBuilder(length + value.numEncodedBytes() * 2); for (int i = 0; i < length; i++) { final int b = value.data[i] & 0xFF; if (value.isEncoded(i)) { if (b == ' ') { buf.append('+'); } else { buf.append(TO_PERCENT_ENCODED_CHARS[b]); } continue; } buf.append((char) b); } return buf.toString(); }
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 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-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 testGetChunk() throws Exception { TestHttpData test = new TestHttpData("test", UTF_8, 0); try { File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); tmpFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmpFile); byte[] bytes = new byte[4096]; PlatformDependent.threadLocalRandom().nextBytes(bytes); try { fos.write(bytes); fos.flush(); } finally { fos.close(); } test.setContent(tmpFile); ByteBuf buf1 = test.getChunk(1024); assertEquals(buf1.readerIndex(), 0); assertEquals(buf1.writerIndex(), 1024); ByteBuf buf2 = test.getChunk(1024); assertEquals(buf2.readerIndex(), 0); assertEquals(buf2.writerIndex(), 1024); assertFalse("Arrays should not be equal", Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2))); } finally { test.delete(); } }
0
Java
CWE-378
Creation of Temporary File With Insecure Permissions
Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.
https://cwe.mitre.org/data/definitions/378.html
vulnerable
public InternetAddress getUserEmail() { return userEmail; }
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 boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) { return cors; }
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 DropFileContainer(final String id, final String mimeType) { super(id); this.mimeType = mimeType; main = new WebMarkupContainer("main"); add(main); }
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 export(@PathVariable("modelId") @ApiParam("模型ID") String modelId, @PathVariable("type") @ApiParam(value = "类型", allowableValues = "bpmn,json", example = "json") ModelType type, @ApiParam(hidden = true) HttpServletResponse response) { Model modelData = repositoryService.getModel(modelId); if (modelData == null) { throw new NotFoundException("模型不存在"); } BpmnJsonConverter jsonConverter = new BpmnJsonConverter(); byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId()); JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource); BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode); // 处理异常 if (bpmnModel.getMainProcess() == null) { throw new UnsupportedOperationException("无法导出模型文件:" + type); } String filename = ""; byte[] exportBytes = null; String mainProcessId = bpmnModel.getMainProcess().getId(); if (type == ModelType.bpmn) { BpmnXMLConverter xmlConverter = new BpmnXMLConverter(); exportBytes = xmlConverter.convertToXML(bpmnModel); filename = mainProcessId + ".bpmn20.xml"; } else if (type == ModelType.json) { exportBytes = modelEditorSource; filename = mainProcessId + ".json"; } else { throw new UnsupportedOperationException("不支持的格式:" + type); } response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8")); /*创建输入流*/ try (ByteArrayInputStream in = new ByteArrayInputStream(exportBytes)) { IOUtils.copy(in, response.getOutputStream()); response.flushBuffer(); } }
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 void testEnc() throws Exception { KeyFactory kFact = KeyFactory.getInstance("DH", "BC"); Key k = kFact.generatePrivate(new PKCS8EncodedKeySpec(samplePrivEnc)); if (!Arrays.areEqual(samplePrivEnc, k.getEncoded())) { fail("private key re-encode failed"); } k = kFact.generatePublic(new X509EncodedKeySpec(samplePubEnc)); if (!Arrays.areEqual(samplePubEnc, k.getEncoded())) { fail("public key re-encode failed"); } k = kFact.generatePublic(new X509EncodedKeySpec(oldPubEnc)); if (!Arrays.areEqual(oldPubEnc, k.getEncoded())) { fail("old public key re-encode failed"); } k = kFact.generatePublic(new X509EncodedKeySpec(oldFullParams)); if (!Arrays.areEqual(oldFullParams, k.getEncoded())) { fail("old full public key re-encode failed"); } }
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 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-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 static void checkSortExpression(Order order) { if (order instanceof JpaOrder && ((JpaOrder) order).isUnsafe()) { return; } if (PUNCTATION_PATTERN.matcher(order.getProperty()).find()) { throw new InvalidDataAccessApiUsageException(String .format("Sort expression '%s' must not contain functions or expressions. Please use JpaSort.unsafe.", order)); } }
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 Map<String, Object> getHelperUtilities() { Map<String, Object> velocityContext = super.getHelperUtilities(); // Date tool velocityContext.put("dateTool", new DateTool()); // Escape tool velocityContext.put("escapeTool", new EscapeTool()); // Iterator tool velocityContext.put("iteratorTool", new IteratorTool()); // List tool velocityContext.put("listTool", new ListTool()); // Math tool velocityContext.put("mathTool", new MathTool()); // Number tool velocityContext.put("numberTool", new NumberTool()); // Portlet preferences velocityContext.put( "velocityPortletPreferences", new TemplatePortletPreferences()); // Sort tool velocityContext.put("sortTool", new SortTool()); // Permissions velocityContext.put( "rolePermission", RolePermissionUtil.getRolePermission()); return velocityContext; }
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
private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException { JSONAware json = null; try { // Check access policy requestHandler.checkAccess(allowDnsReverseLookup ? pReq.getRemoteHost() : null, pReq.getRemoteAddr(), getOriginOrReferer(pReq)); // Remember the agent URL upon the first request. Needed for discovery updateAgentDetailsIfNeeded(pReq); // Dispatch for the proper HTTP request method json = handleSecurely(pReqHandler, pReq, pResp); } catch (Throwable exp) { json = requestHandler.handleThrowable( exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp); } finally { setCorsHeader(pReq, pResp); if (json == null) { json = requestHandler.handleThrowable(new Exception("Internal error while handling an exception")); } sendResponse(pResp, pReq, json); } }
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 static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new ECDSA5Test()); }
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 testByteSerialization() throws Exception { final IBaseDataObject d = DataObjectFactory.getInstance("abc".getBytes(), "testfile", Form.UNKNOWN); final byte[] bytes = PayloadUtil.serializeToBytes(d); final String s1 = new String(bytes); assertTrue("Serializedion must include data from payload", s1.indexOf("abc") > -1); }
0
Java
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
public static SecretKey deriveSharedSecret(final ECPublicKey publicKey, final ECPrivateKey privateKey, final Provider provider) throws JOSEException { // Get an ECDH key agreement instance from the JCA provider KeyAgreement keyAgreement; try { if (provider != null) { keyAgreement = KeyAgreement.getInstance("ECDH", provider); } else { keyAgreement = KeyAgreement.getInstance("ECDH"); } } catch (NoSuchAlgorithmException e) { throw new JOSEException("Couldn't get an ECDH key agreement instance: " + e.getMessage(), e); } try { keyAgreement.init(privateKey); keyAgreement.doPhase(publicKey, true); } catch (InvalidKeyException e) { throw new JOSEException("Invalid key for ECDH key agreement: " + e.getMessage(), e); } return new SecretKeySpec(keyAgreement.generateSecret(), "AES"); }
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 install( String displayName, String description, String[] dependencies, String account, String password, String config) throws URISyntaxException { String javaHome = System.getProperty("java.home"); String javaBinary = "\"" + javaHome + "\\bin\\java.exe\""; File jar = new File(WindowsService.class.getProtectionDomain().getCodeSource().getLocation().toURI()); String command = javaBinary + " -Duser.dir=\"" + jar.getParentFile().getAbsolutePath() + "\"" + " -jar \"" + jar.getAbsolutePath() + "\"" + " --service \"" + config + "\""; StringBuilder dep = new StringBuilder(); if (dependencies != null) { for (String s : dependencies) { dep.append(s); dep.append("\0"); } } dep.append("\0"); SERVICE_DESCRIPTION desc = new SERVICE_DESCRIPTION(); desc.lpDescription = description; SC_HANDLE serviceManager = openServiceControlManager(null, Winsvc.SC_MANAGER_ALL_ACCESS); if (serviceManager != null) { SC_HANDLE service = ADVAPI_32.CreateService(serviceManager, serviceName, displayName, Winsvc.SERVICE_ALL_ACCESS, WinNT.SERVICE_WIN32_OWN_PROCESS, WinNT.SERVICE_AUTO_START, WinNT.SERVICE_ERROR_NORMAL, command, null, null, dep.toString(), account, password); if (service != null) { ADVAPI_32.ChangeServiceConfig2(service, Winsvc.SERVICE_CONFIG_DESCRIPTION, desc); ADVAPI_32.CloseServiceHandle(service); } ADVAPI_32.CloseServiceHandle(serviceManager); } }
1
Java
CWE-428
Unquoted Search Path or Element
The product uses a search path that contains an unquoted element, in which the element contains whitespace or other separators. This can cause the product to access resources in a parent path.
https://cwe.mitre.org/data/definitions/428.html
safe
public void testValidUserIds() { testInvalidUserId("John-Doe",false); testInvalidUserId("Jane/Doe",false); testInvalidUserId("John.Doe",false); testInvalidUserId("Jane#Doe", false); testInvalidUserId("John@Döe.com", false); testInvalidUserId("JohnDoé", false); }
1
Java
CWE-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
void empty() { final PathAndQuery res = PathAndQuery.parse(null); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/"); assertThat(res.query()).isNull(); final PathAndQuery res2 = PathAndQuery.parse(""); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/"); assertThat(res2.query()).isNull(); final PathAndQuery res3 = PathAndQuery.parse("?"); assertThat(res3).isNotNull(); assertThat(res3.path()).isEqualTo("/"); assertThat(res3.query()).isEqualTo(""); }
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 Secret getDefaultValueAsSecret() { return defaultValue; }
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 boolean isValid(Object value, ConstraintValidatorContext context) { final ViolationCollector collector = new ViolationCollector(context, escapeExpressions); context.disableDefaultConstraintViolation(); for (ValidationCaller caller : methodMap.computeIfAbsent(value.getClass(), this::findMethods)) { caller.setValidationObject(value); caller.call(collector); } return !collector.hasViolationOccurred(); }
1
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
safe
public void subValidateFail(ViolationCollector col) { col.addViolation(FAILED + "subclass"); }
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 AsciiString create(String name) { return AsciiString.cached(Ascii.toLowerCase(name)); }
0
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (plaintextOffset > plaintext.length) space = 0; else space = plaintext.length - plaintextOffset; if (!haskey) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); setup(ad); 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-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
public void addViolation(String propertyName, Integer index, String message) { violationOccurred = true; String messageTemplate = escapeEl(message); context.buildConstraintViolationWithTemplate(messageTemplate) .addPropertyNode(propertyName) .addBeanNode().inIterable().atIndex(index) .addConstraintViolation(); }
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 getContent(SxSource sxSource, FilesystemExportContext exportContext) { String content; // We know we're inside a SX file located at "<S|J>sx/<Space>/<Page>/<s|j>sx<NNN>.<css|js>". Inside this CSS // there can be URLs and we need to ensure that the prefix for these URLs lead to the root of the path, i.e. // 3 levels up ("../../../"). // To make this happen we reuse the Doc Parent Level from FileSystemExportContext to a fixed value of 3. // We also make sure to put back the original value int originalDocParentLevel = exportContext.getDocParentLevel(); try { exportContext.setDocParentLevels(3); content = sxSource.getContent(); } finally { exportContext.setDocParentLevels(originalDocParentLevel); } return content; }
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 void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); 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"); } }
0
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
vulnerable
public 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(); }
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 SecureIntrospector(String[] badClasses, String[] badPackages, Logger log) { super(badClasses, badPackages, log); this.secureClassMethods.add("getname"); this.secureClassMethods.add("getName"); this.secureClassMethods.add("getsimpleName"); this.secureClassMethods.add("getSimpleName"); this.secureClassMethods.add("isarray"); this.secureClassMethods.add("isArray"); this.secureClassMethods.add("isassignablefrom"); this.secureClassMethods.add("isAssignableFrom"); this.secureClassMethods.add("isenum"); this.secureClassMethods.add("isEnum"); this.secureClassMethods.add("isinstance"); this.secureClassMethods.add("isInstance"); this.secureClassMethods.add("isinterface"); this.secureClassMethods.add("isInterface"); this.secureClassMethods.add("islocalClass"); this.secureClassMethods.add("isLocalClass"); this.secureClassMethods.add("ismemberclass"); this.secureClassMethods.add("isMemberClass"); this.secureClassMethods.add("isprimitive"); this.secureClassMethods.add("isPrimitive"); this.secureClassMethods.add("issynthetic"); this.secureClassMethods.add("isSynthetic"); this.secureClassMethods.add("getEnumConstants"); // TODO: add more when needed }
0
Java
CWE-668
Exposure of Resource to Wrong Sphere
The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource.
https://cwe.mitre.org/data/definitions/668.html
vulnerable
public byte[] readBinary() throws TException { int size = readI32(); ensureContainerHasEnough(size, TType.BYTE); checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return buf; }
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
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { String oldName = request.getParameter("groupName"); String newName = request.getParameter("newName"); if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) { m_groupRepository.renameGroup(oldName, newName); } return listGroups(request, response); }
0
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
private List<GHPoint> getPointsFromRequest(HttpServletRequest httpServletRequest, String profile) { String url = httpServletRequest.getRequestURI(); url = url.replaceFirst("/navigate/directions/v5/gh/" + profile + "/", ""); url = url.replaceAll("\\?[*]", ""); String[] pointStrings = url.split(";"); List<GHPoint> points = new ArrayList<>(pointStrings.length); for (int i = 0; i < pointStrings.length; i++) { points.add(GHPoint.fromStringLonLat(pointStrings[i])); } return points; }
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 Map<String, String> handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) { Map<String,String> ret = new HashMap<String, String>(); if (pOrigin != null && backendManager.isOriginAllowed(pOrigin,false)) { // CORS is allowed, we set exactly the origin in the header, so there are no problems with authentication ret.put("Access-Control-Allow-Origin","null".equals(pOrigin) ? "*" : pOrigin); if (pRequestHeaders != null) { ret.put("Access-Control-Allow-Headers",pRequestHeaders); } // Fix for CORS with authentication (#104) ret.put("Access-Control-Allow-Credentials","true"); // Allow for one year. Changes in access.xml are reflected directly in the cors request itself ret.put("Access-Control-Allow-Max-Age","" + 3600 * 24 * 365); } return ret; }
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 validateFail(ViolationCollector col) { col.addViolation("${'value'}"); col.addViolation("$\\A{1+1}"); col.addViolation("{value}", Collections.singletonMap("value", "TEST")); col.addViolation("${'property'}", "${'value'}"); col.addViolation("${'property'}", 1, "${'value'}"); col.addViolation("${'property'}", "${'key'}", "${'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 void testExcludesUri() { final Collection<String> patterns = new ArrayList<String>() {{ add( "git://**" ); add( "**/repo/**" ); }}; Assert.assertFalse( excludes( patterns, URI.create( "file:///Users/home" ) ) ); Assert.assertTrue( excludes( patterns, URI.create( "git://antpathmatcher" ) ) ); Assert.assertTrue( excludes( patterns, URI.create( "git://master@antpathmatcher" ) ) ); }
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 SAXReader() { }
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 ResourceEvaluation evaluate(File file, String filename) { ResourceEvaluation eval = new ResourceEvaluation(); try { ImsManifestFileFilter visitor = new ImsManifestFileFilter(); Path fPath = PathUtils.visit(file, filename, visitor); if(visitor.isValid()) { Path realManifestPath = visitor.getManifestPath(); Path manifestPath = fPath.resolve(realManifestPath); RootSearcher rootSearcher = new RootSearcher(); Files.walkFileTree(fPath, rootSearcher); if(rootSearcher.foundRoot()) { manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST); } else { manifestPath = fPath.resolve(IMS_MANIFEST); } QTI21ContentPackage cp = new QTI21ContentPackage(manifestPath); if(validateImsManifest(cp, new PathResourceLocator(manifestPath.getParent()))) { eval.setValid(true); } else { eval.setValid(false); } } else { eval.setValid(false); } PathUtils.closeSubsequentFS(fPath); } catch (IOException | IllegalArgumentException e) { log.error("", e); eval.setValid(false); } return eval; }
0
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
protected DataSource createDataSource(Map<String, ?> params, SQLDialect dialect) throws IOException { String jndiName = (String) JNDI_REFNAME.lookUp(params); if (jndiName == null) throw new IOException("Missing " + JNDI_REFNAME.description); Context ctx = null; DataSource ds = null; try { ctx = GeoTools.getInitialContext(); } catch (NamingException e) { throw new RuntimeException(e); } try { ds = (DataSource) ctx.lookup(jndiName); } catch (NamingException e1) { // check if the user did not specify "java:comp/env" // and this code is running in a J2EE environment try { if (jndiName.startsWith(J2EERootContext) == false) { ds = (DataSource) ctx.lookup(J2EERootContext + jndiName); // success --> issue a waring Logger.getLogger(this.getClass().getName()) .log( Level.WARNING, "Using " + J2EERootContext + jndiName + " instead of " + jndiName + " would avoid an unnecessary JNDI lookup"); } } catch (NamingException e2) { // do nothing, was only a try } } if (ds == null) throw new IOException("Cannot find JNDI data source: " + jndiName); else return ds; }
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 testContentLengthHeaderAndChunked() { String requestStr = "POST / HTTP/1.1\r\n" + "Host: example.com\r\n" + "Connection: close\r\n" + "Content-Length: 5\r\n" + "Transfer-Encoding: chunked\r\n\r\n" + "0\r\n\r\n"; EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestDecoder()); assertTrue(channel.writeInbound(Unpooled.copiedBuffer(requestStr, CharsetUtil.US_ASCII))); HttpRequest request = channel.readInbound(); assertFalse(request.decoderResult().isFailure()); assertTrue(request.headers().contains("Transfer-Encoding", "chunked", false)); assertFalse(request.headers().contains("Content-Length")); LastHttpContent c = channel.readInbound(); c.release(); assertFalse(channel.finish()); }
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 PathAndQuery splitPathAndQuery(@Nullable final String pathAndQuery) { final Bytes path; final Bytes query; if (pathAndQuery == null) { return ROOT_PATH_QUERY; } // Split by the first '?'. final int queryPos = pathAndQuery.indexOf('?'); if (queryPos >= 0) { if ((path = decodePercentsAndEncodeToUtf8( pathAndQuery, 0, queryPos, true)) == null) { return null; } if ((query = decodePercentsAndEncodeToUtf8( pathAndQuery, queryPos + 1, pathAndQuery.length(), false)) == null) { return null; } } else { if ((path = decodePercentsAndEncodeToUtf8( pathAndQuery, 0, pathAndQuery.length(), true)) == null) { return null; } query = null; } if (path.data[0] != '/') { // Do not accept a relative path. return null; } // Reject the prohibited patterns. if (pathContainsDoubleDots(path)) { return null; } return new PathAndQuery(encodeToPercents(path, true), query != null ? encodeToPercents(query, false) : null); }
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 accessDenied() { expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(false); replay(backend); handler.checkAccess("localhost", "127.0.0.1",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 giveWarningIfNoValidationMethods() { assertThat(ConstraintViolations.format(validator.validate(new NoValidations()))) .isEmpty(); assertThat(TestLoggerFactory.getAllLoggingEvents()) .containsExactlyInAnyOrder( new LoggingEvent( Level.WARN, "The class {} is annotated with @SelfValidating but contains no valid methods that are annotated with @SelfValidation", NoValidations.class ) ); }
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 HtmlRenderable htmlBody() { return HtmlElement.li().content( HtmlElement.span(HtmlAttribute.cssClass("artifact")).content( HtmlElement.a(HtmlAttribute.href(getUrl())) .content(getFileName()) ) ); }
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 static Object readObject(XStream xStream, String xml) { try(InputStream is = new ByteArrayInputStream(xml.getBytes(ENCODING))) { return readObject(xStream, is); } catch (Exception e) { throw new OLATRuntimeException(XStreamHelper.class, "could not read Object from string: " + xml, e); } }
0
Java
CWE-91
XML Injection (aka Blind XPath Injection)
The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system.
https://cwe.mitre.org/data/definitions/91.html
vulnerable
public SAXReader(XMLReader xmlReader, boolean validating) { this.xmlReader = xmlReader; 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
private void updateSecureSessionFlag() { try { ServletContext context = Jenkins.getInstance().servletContext; Method m; try { m = context.getClass().getMethod("getSessionCookieConfig"); } catch (NoSuchMethodException x) { // 3.0+ LOGGER.log(Level.FINE, "Failed to set secure cookie flag", x); return; } Object sessionCookieConfig = m.invoke(context); Class scc = Class.forName("javax.servlet.SessionCookieConfig"); Method setSecure = scc.getMethod("setSecure", boolean.class); boolean v = fixNull(jenkinsUrl).startsWith("https"); setSecure.invoke(sessionCookieConfig, v); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof IllegalStateException) { // servlet 3.0 spec seems to prohibit this from getting set at runtime, // though Winstone is happy to accept i. see JENKINS-25019 return; } LOGGER.log(Level.WARNING, "Failed to set secure cookie flag", e); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to set secure cookie flag", e); } }
1
Java
CWE-254
7PK - Security Features
Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management.
https://cwe.mitre.org/data/definitions/254.html
safe
void sort_directory(struct dir *dir) { struct dir_ent *cur, *l1, *l2, *next; int len1, len2, stride = 1; if(dir->dir_count < 2) return; /* * We can consider our linked-list to be made up of stride length * sublists. Eacn iteration around this loop merges adjacent * stride length sublists into larger 2*stride sublists. We stop * when stride becomes equal to the entire list. * * Initially stride = 1 (by definition a sublist of 1 is sorted), and * these 1 element sublists are merged into 2 element sublists, which * are then merged into 4 element sublists and so on. */ do { l2 = dir->dirs; /* head of current linked list */ cur = NULL; /* empty output list */ /* * Iterate through the linked list, merging adjacent sublists. * On each interation l2 points to the next sublist pair to be * merged (if there's only one sublist left this is simply added * to the output list) */ while(l2) { l1 = l2; for(len1 = 0; l2 && len1 < stride; len1 ++, l2 = l2->next); len2 = stride; /* * l1 points to first sublist. * l2 points to second sublist. * Merge them onto the output list */ while(len1 && l2 && len2) { if(strcmp(l1->name, l2->name) <= 0) { next = l1; l1 = l1->next; len1 --; } else { next = l2; l2 = l2->next; len2 --; } if(cur) { cur->next = next; cur = next; } else dir->dirs = cur = next; } /* * One sublist is now empty, copy the other one onto the * output list */ for(; len1; len1 --, l1 = l1->next) { if(cur) { cur->next = l1; cur = l1; } else dir->dirs = cur = l1; } for(; l2 && len2; len2 --, l2 = l2->next) { if(cur) { cur->next = l2; cur = l2; } else dir->dirs = cur = l2; } } cur->next = NULL; stride = stride << 1; } while(stride < dir->dir_count); }
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
final void setObject(CharSequence name, Object... values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); final int h = normalizedName.hashCode(); final int i = index(h); remove0(h, i, normalizedName); for (Object v: values) { requireNonNullElement(values, v); add0(h, i, normalizedName, fromObject(v)); } }
0
Java
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
public void testComputeLength() throws IntegerOverflowException { byte[] aad = new byte[]{0, 1, 2, 3}; // 32 bits byte[] expectedBitLength = new byte[]{0, 0, 0, 0, 0, 0, 0, 32}; assertTrue(Arrays.equals(expectedBitLength, AAD.computeLength(aad))); }
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
private File doDownload(String driverFileUrl, String filePath) { Path path = Path.of(filePath); // create parent directory if (Files.notExists(path)) { path.getParent().toFile().mkdirs(); try { Files.createFile(path); } catch (IOException e) { log.error("create file error " + filePath, e); throw DomainErrors.DOWNLOAD_DRIVER_ERROR.exception(e.getMessage()); } } // download try { return restTemplate.execute(driverFileUrl, HttpMethod.GET, null, response -> { if (response.getStatusCode().is2xxSuccessful()) { File file = path.toFile(); FileOutputStream out = new FileOutputStream(file); StreamUtils.copy(response.getBody(), out); IOUtils.closeQuietly(out, ex -> log.error("close file error", ex)); log.info("{} download success ", filePath); return file; } else { log.error("{} download error from {}: {} ", filePath, driverFileUrl, response); throw DomainErrors.DOWNLOAD_DRIVER_ERROR.exception("驱动下载失败:" + response.getStatusCode() + ", " + response.getStatusText()); } }); } catch (IllegalArgumentException e) { log.error(filePath + " download driver error", e); throw DomainErrors.DOWNLOAD_DRIVER_ERROR.exception(e.getMessage()); } }
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 TList readListBegin() throws TException { byte size_and_type = readByte(); int size = (size_and_type >> 4) & 0x0f; if (size == 15) { size = readVarint32(); } byte type = getTType(size_and_type); ensureContainerHasEnough(size, type); return new TList(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
static void setProperty(SchemaFactory schemaFactory, String propertyName) throws SAXException { try { schemaFactory.setProperty(propertyName, ""); } catch (SAXException e) { if (Boolean.getBoolean(SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES)) { LOGGER.warning("Enabling XXE protection failed. The property " + propertyName + " is not supported by the SchemaFactory. The " + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES + " system property is used so the XML processing continues in the UNSECURE mode" + " with XXE protection disabled!!!"); } else { LOGGER.severe("Enabling XXE protection failed. The property " + propertyName + " is not supported by the SchemaFactory. This usually mean an outdated XML processor" + " is present on the classpath (e.g. Xerces, Xalan). If you are not able to resolve the issue by" + " fixing the classpath, the " + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES + " system property can be used to disable XML External Entity protections." + " We don't recommend disabling the XXE as such the XML processor configuration is unsecure!!!", e); throw 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 testImportZipSigAndEmptyConsumerZip() 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"); ZipOutputStream cezip = new ZipOutputStream(new FileOutputStream(ceArchive)); cezip.putNextEntry(new ZipEntry("This is just a zip file with no content")); cezip.close(); addFileToArchive(out, ceArchive); out.close(); try { i.loadExport(owner, archive, co); } catch (ImportExtractionException e) { assertEquals(e.getMessage(), i18n.tr("The consumer_export " + "archive has no contents")); 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 testCBCPaddingOracleAttack() throws Exception { SecretKey inputKey = new SecretKeySpec(INPUT_KEY_256, "AES"); Assert.assertArrayEquals("Input key", INPUT_KEY_256, inputKey.getEncoded()); AuthenticatedCipherText act = AESCBC.encryptAuthenticated(inputKey, IV, PLAIN_TEXT, AAD, null, null); byte[] cipherText = act.getCipherText(); // Now change the cipher text to make CBC padding invalid. cipherText[cipherText.length - 1] ^= 0x01; try { AESCBC.decryptAuthenticated(inputKey, IV, cipherText, AAD, act.getAuthenticationTag(), null, null); } catch (JOSEException e) { assertEquals("MAC check failed", e.getMessage()); } }
1
Java
CWE-354
Improper Validation of Integrity Check Value
The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
https://cwe.mitre.org/data/definitions/354.html
safe
public OutputStream getOutputStream(boolean append) { return null; }
0
Java
CWE-91
XML Injection (aka Blind XPath Injection)
The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system.
https://cwe.mitre.org/data/definitions/91.html
vulnerable
public void testSelectByOperations() { JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyOperations(KeyOperation.SIGN, KeyOperation.VERIFY).build()); List<JWK> keyList = new ArrayList<>(); keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1") .keyOperations(new HashSet<>(Arrays.asList(KeyOperation.SIGN, KeyOperation.VERIFY))).build()); keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()); JWKSet jwkSet = new JWKSet(keyList); List<JWK> matches = selector.select(jwkSet); RSAKey key1 = (RSAKey)matches.get(0); assertEquals(KeyType.RSA, key1.getKeyType()); assertEquals("1", key1.getKeyID()); assertEquals(1, matches.size()); }
0
Java
CWE-347
Improper Verification of Cryptographic Signature
The software does not verify, or incorrectly verifies, the cryptographic signature for data.
https://cwe.mitre.org/data/definitions/347.html
vulnerable
public void testSetContentFromFile() throws Exception { TestHttpData test = new TestHttpData("test", UTF_8, 0); try { File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null); tmpFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmpFile); byte[] bytes = new byte[4096]; PlatformDependent.threadLocalRandom().nextBytes(bytes); try { fos.write(bytes); fos.flush(); } finally { fos.close(); } test.setContent(tmpFile); ByteBuf buf = test.getByteBuf(); assertEquals(buf.readerIndex(), 0); assertEquals(buf.writerIndex(), bytes.length); assertArrayEquals(bytes, test.get()); assertArrayEquals(bytes, ByteBufUtil.getBytes(buf)); } finally { //release the ByteBuf test.delete(); } }
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 ClassPathResource(String path, ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); Assert.state(doesNotContainFileColon(path), "Path must not contain 'file:'"); String pathToUse = StringUtils.cleanPath(path); if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } this.path = pathToUse; this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); }
0
Java
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
public static Map<String, String> getSAMLAttributes() { Map<String, String> attributes = new HashMap<>(); attributes.put(SAML_CLIENT_SIGNATURE, "true"); attributes.put(SAML_AUTHNSTATEMENT, "true"); attributes.put(SAML_FORCE_POST_BINDING, "true"); attributes.put(SAML_SERVER_SIGNATURE, "true"); attributes.put(SAML_SIGNATURE_ALGORITHM, "RSA_SHA256"); attributes.put(SAML_FORCE_NAME_ID_FORMAT, "false"); attributes.put(SAML_NAME_ID_FORMAT, "username"); attributes.put(SAML_ALLOW_ECP_FLOW, "false"); attributes.put(SamlConfigAttributes.SAML_ARTIFACT_BINDING_IDENTIFIER, ArtifactBindingUtils.computeArtifactBindingIdentifierString("saml")); return attributes; }
1
Java
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
safe
public String getShortDescription() { if(note != null) { try { return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, Jenkins.getInstance().getMarkupFormatter().translate(note)); } catch (IOException x) { // ignore } } return Messages.Cause_RemoteCause_ShortDescription(addr); }
1
Java
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
public int doFinal(byte[] out, int outOff) throws DataLengthException, IllegalStateException { try { return ccm.doFinal(out, 0); } catch (InvalidCipherTextException e) { throw new IllegalStateException("exception on doFinal()", e); } }
0
Java
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
vulnerable
private void cleanupSSLFD() { if (!closed_fd && ssl_fd != null) { try { SSL.RemoveCallbacks(ssl_fd); PR.Close(ssl_fd); ssl_fd.close(); } catch (Exception e) { debug("Got exception trying to cleanup SSLFD: " + e.getMessage()); } finally { closed_fd = true; } } if (read_buf != null) { Buffer.Free(read_buf); read_buf = null; } if (write_buf != null) { Buffer.Free(write_buf); write_buf = null; } }
0
Java
NVD-CWE-noinfo
null
null
null
vulnerable
public Element handle(Element request, Map<String, Object> context) throws ServiceException { ZimbraSoapContext zsc = getZimbraSoapContext(context); Account account = getRequestedAccount(getZimbraSoapContext(context)); if (!canAccessAccount(zsc, account)) throw ServiceException.PERM_DENIED("can not access account"); String name = request.getAttribute(AccountConstants.E_NAME); String typeStr = request.getAttribute(AccountConstants.A_TYPE, "account"); GalSearchType type = GalSearchType.fromString(typeStr); boolean needCanExpand = request.getAttributeBool(AccountConstants.A_NEED_EXP, false); String galAcctId = request.getAttribute(AccountConstants.A_GAL_ACCOUNT_ID, null); GalSearchParams params = new GalSearchParams(account, zsc); params.setType(type); params.setRequest(request); params.setQuery(name); params.setLimit(account.getContactAutoCompleteMaxResults()); params.setNeedCanExpand(needCanExpand); params.setResponseName(AccountConstants.AUTO_COMPLETE_GAL_RESPONSE); if (galAcctId != null) { Account galAccount = Provisioning.getInstance().getAccountById(galAcctId); if (galAccount != null && (!account.getDomainId().equals(galAccount.getDomainId()))) { throw ServiceException .PERM_DENIED("can not access galsync account of different domain"); } params.setGalSyncAccount(galAccount); } GalSearchControl gal = new GalSearchControl(params); gal.autocomplete(); return params.getResultCallback().getResponse(); }
1
Java
CWE-862
Missing Authorization
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
private static boolean appendOneByte(Bytes buf, int cp, boolean wasSlash, boolean isPath) { if (cp == 0x7F) { // Reject the control character: 0x7F return false; } if (cp >>> 5 == 0) { // Reject the control characters: 0x00..0x1F if (isPath) { return false; } else if (cp != 0x0A && cp != 0x0D && cp != 0x09) { // .. except 0x0A (LF), 0x0D (CR) and 0x09 (TAB) because they are used in a form. return false; } } if (cp == '/' && isPath) { if (!wasSlash) { buf.ensure(1); buf.add((byte) '/'); } else { // Remove the consecutive slashes: '/path//with///consecutive////slashes'. } } else { buf.ensure(1); buf.add((byte) cp); } return true; }
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 setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; }
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 X509HostnameVerifier createHostNameVerifier() { X509HostnameVerifier verifier = new X509HostnameVerifier() { /** * {@InheritDoc} * * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSocket) */ public void verify(String host, SSLSocket ssl) throws IOException { logger.trace("Skipping SSL host name check on {}", host); } /** * {@InheritDoc} * * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.security.cert.X509Certificate) */ public void verify(String host, X509Certificate xc) throws SSLException { logger.trace("Skipping X509 certificate host name check on {}", host); } /** * {@InheritDoc} * * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.lang.String[], * java.lang.String[]) */ public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { logger.trace("Skipping DNS host name check on {}", host); } /** * {@InheritDoc} * * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSession) */ public boolean verify(String host, SSLSession ssl) { logger.trace("Skipping SSL session host name check on {}", host); return true; } }; return verifier; }
0
Java
CWE-346
Origin Validation Error
The software does not properly verify that the source of data or communication is valid.
https://cwe.mitre.org/data/definitions/346.html
vulnerable
protected void after() { ConfidentialStore.TEST.set(null); try { Util.deleteRecursive(tmp); } catch (IOException e) { throw new Error(e); } }
1
Java
NVD-CWE-noinfo
null
null
null
safe
private List<GlossaryItem> loadGlossaryItemListFromFile(VFSLeaf glossaryFile) { List<GlossaryItem> glossaryItemList = new ArrayList<>(); if (glossaryFile == null) { return new ArrayList<>(); } Object glossObj = XStreamHelper.readObject(xstreamReader, glossaryFile); if (glossObj instanceof ArrayList) { ArrayList<GlossaryItem> glossItemsFromFile = (ArrayList<GlossaryItem>) glossObj; glossaryItemList.addAll(glossItemsFromFile); } else { log.error("The Glossary-XML-File " + glossaryFile.toString() + " seems not to be correct!"); } Collections.sort(glossaryItemList); return glossaryItemList; }
0
Java
CWE-91
XML Injection (aka Blind XPath Injection)
The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system.
https://cwe.mitre.org/data/definitions/91.html
vulnerable
public void testPathWithShellExpansionStrings() throws Exception { File dir = new File( System.getProperty( "basedir" ), "target/test/dollar$test" ); createAndCallScript( dir, "echo Quoted" ); }
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
static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source) { Ruby runtime = context.getRuntime(); XmlRelaxng xmlRelaxng = (XmlRelaxng) NokogiriService.XML_RELAXNG_ALLOCATOR.allocate(runtime, klazz); xmlRelaxng.setInstanceVariable("@errors", runtime.newEmptyArray()); try { Schema schema = xmlRelaxng.getSchema(source, context); xmlRelaxng.setVerifier(schema.newVerifier()); return xmlRelaxng; } catch (VerifierConfigurationException 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 validateCallbackIfGiven(HttpServletRequest pReq) { String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue()); if (callback != null && !MimeTypeUtil.isValidCallback(callback)) { throw new IllegalArgumentException("Invalid callback name given, which must be a valid javascript function name"); } }
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 void initializeVelocity() { if (velocityEngine == null) { velocityEngine = new VelocityEngine(); Properties props = new Properties(); props.setProperty(RuntimeConstants.RUNTIME_LOG, "startup_wizard_vel.log"); // Linux requires setting logging properties to initialize Velocity Context. props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.CommonsLogLogChute"); props.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME, "initial_wizard_velocity"); // so the vm pages can import the header/footer props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class"); props.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader"); props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); try { velocityEngine.init(props); } catch (Exception e) { log.error("velocity init failed, because: " + e); } } }
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 translate(ItemFrameDropItemPacket packet, GeyserSession session) { Entity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); if (entity != null) { ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking()); session.sendDownstreamPacket(interactPacket); } }
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 headerMultipleContentLengthValidationShouldPropagate() { LastInboundHandler inboundHandler = new LastInboundHandler(); request.addLong(HttpHeaderNames.CONTENT_LENGTH, 0); request.addLong(HttpHeaderNames.CONTENT_LENGTH, 1); Http2StreamChannel channel = newInboundStream(3, false, inboundHandler); try { inboundHandler.checkException(); fail(); } catch (Exception e) { assertThat(e, CoreMatchers.<Exception>instanceOf(StreamException.class)); } assertNull(inboundHandler.readInbound()); assertFalse(channel.isActive()); }
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 setExpirationTime(int expirationTime) { this.expirationTime = expirationTime; }
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 DefaultFileSystemResourceLoader(File baseDirPath) { this.baseDirPath = Optional.of(baseDirPath.toPath()); }
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 accessDenied() { expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(false); replay(backend); handler.checkClientIPAccess("localhost","127.0.0.1"); }
0
Java
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
vulnerable
public void testHeaderNameEndsWithControlChar1c() { testHeaderNameEndsWithControlChar(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 boolean checkObjectExecutePermission(Class clazz, String methodName) { if (Class.class.isAssignableFrom(clazz) && methodName != null && this.secureClassMethods.contains(methodName)) { return true; } else { return super.checkObjectExecutePermission(clazz, methodName); } }
0
Java
CWE-668
Exposure of Resource to Wrong Sphere
The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource.
https://cwe.mitre.org/data/definitions/668.html
vulnerable
public Stream(final InputStream inner) { this.inner = inner; }
1
Java
CWE-732
Incorrect Permission Assignment for Critical Resource
The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.
https://cwe.mitre.org/data/definitions/732.html
safe
public void testInvalidUserId(final String userId, final boolean mustFail) { adminPage(); findElementByLink("Configure Users, Groups and On-Call Roles").click(); findElementByLink("Configure Users").click(); findElementByLink("Add new user").click(); enterText(By.id("userID"), userId); enterText(By.id("pass1"), "SmokeTestPassword"); enterText(By.id("pass2"), "SmokeTestPassword"); findElementByXpath("//button[@type='submit' and text()='OK']").click(); if (mustFail) { try { final Alert alert = wait.withTimeout(Duration.of(5, ChronoUnit.SECONDS)).until(ExpectedConditions.alertIsPresent()); alert.dismiss(); } catch (final Exception e) { LOG.debug("Got an exception waiting for a 'invalid user ID' alert.", e); throw e; } } else { wait.until(ExpectedConditions.elementToBeClickable(By.name("finish"))); } }
1
Java
CWE-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 static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } } };
0
Java
CWE-306
Missing Authentication for Critical Function
The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
public void sendError(int sc, String msg) throws IOException { if (isIncluding()) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "IncludeResponse.Error", new String[] { "" + sc, msg }); return; } Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WinstoneResponse.SendingError", new String[] { "" + sc, msg }); if ((this.webAppConfig != null) && (this.req != null)) { RequestDispatcher rd = this.webAppConfig .getErrorDispatcherByCode(req.getRequestURI(), sc, msg, null); if (rd != null) { try { rd.forward(this.req, this); return; } catch (IllegalStateException err) { throw err; } catch (IOException err) { throw err; } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneResponse.ErrorInErrorPage", new String[] { rd.getName(), sc + "" }, err); return; } } } // If we are here there was no webapp and/or no request object, so // show the default error page if (this.errorStatusCode == null) { this.statusCode = sc; } String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage", new String[] { sc + "", URIUtil.htmlEscape(msg == null ? "" : msg), "", Launcher.RESOURCES.getString("ServerVersion"), "" + new Date() }); setContentLength(output.getBytes(getCharacterEncoding()).length); Writer out = getWriter(); out.write(output); out.flush(); }
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 ConsoleAnnotator createAnnotator(StaplerRequest req) throws IOException { try { String base64 = req!=null ? req.getHeader("X-ConsoleAnnotator") : null; if (base64!=null) { Cipher sym = Secret.getCipher("AES"); sym.init(Cipher.DECRYPT_MODE, Jenkins.getInstance().getSecretKeyAsAES128()); ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream( new CipherInputStream(new ByteArrayInputStream(Base64.decode(base64.toCharArray())),sym)), Jenkins.getInstance().pluginManager.uberClassLoader); try { long timestamp = ois.readLong(); if (TimeUnit2.HOURS.toMillis(1) > abs(System.currentTimeMillis()-timestamp)) // don't deserialize something too old to prevent a replay attack return (ConsoleAnnotator)ois.readObject(); } finally { ois.close(); } } } catch (GeneralSecurityException e) { throw new IOException2(e); } catch (ClassNotFoundException e) { throw new IOException2(e); } // start from scratch return ConsoleAnnotator.initial(context==null ? null : context.getClass()); }
0
Java
NVD-CWE-noinfo
null
null
null
vulnerable
public void translate(EntityEventPacket packet, GeyserSession session) { switch (packet.getType()) { case EATING_ITEM: // Resend the packet so we get the eating sounds session.sendUpstreamPacket(packet); return; case COMPLETE_TRADE: ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData()); session.sendDownstreamPacket(selectTradePacket); session.scheduleInEventLoop(() -> { Entity villager = session.getPlayerEntity(); Inventory openInventory = session.getOpenInventory(); if (openInventory instanceof MerchantContainer) { MerchantContainer merchantInventory = (MerchantContainer) openInventory; VillagerTrade[] trades = merchantInventory.getVillagerTrades(); if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) { VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()]; openInventory.setItem(2, GeyserItemStack.from(trade.getOutput()), session); villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP)); villager.updateBedrockMetadata(session); } } }, 100, TimeUnit.MILLISECONDS); return; } session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + packet.toString()); }
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