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 |
---|---|---|---|---|---|---|---|
final void addObject(CharSequence name, Iterable<?> values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
for (Object v : values) {
requireNonNullElement(values, v);
addObject(normalizedName, v);
}
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public boolean isCorsAccessAllowed(String pOrigin) {
return isAllowed;
} | 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 handle(HttpExchange pExchange) throws IOException {
if (requestHandler == null) {
throw new IllegalStateException("Handler not yet started");
}
JSONAware json = null;
URI uri = pExchange.getRequestURI();
ParsedUri parsedUri = new ParsedUri(uri,context);
try {
// Check access policy
InetSocketAddress address = pExchange.getRemoteAddress();
requestHandler.checkAccess(address.getHostName(), address.getAddress().getHostAddress(),
extractOriginOrReferer(pExchange));
String method = pExchange.getRequestMethod();
// Dispatch for the proper HTTP request method
if ("GET".equalsIgnoreCase(method)) {
setHeaders(pExchange);
json = executeGetRequest(parsedUri);
} else if ("POST".equalsIgnoreCase(method)) {
setHeaders(pExchange);
json = executePostRequest(pExchange, parsedUri);
} else if ("OPTIONS".equalsIgnoreCase(method)) {
performCorsPreflightCheck(pExchange);
} else {
throw new IllegalArgumentException("HTTP Method " + method + " is not supported.");
}
} catch (Throwable exp) {
json = requestHandler.handleThrowable(
exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
} finally {
sendResponse(pExchange,parsedUri,json);
}
} | 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 RDFDescription parseAsResource(Node node) {
// See: http://www.w3.org/TR/REC-rdf-syntax/#section-Syntax-parsetype-resource
List<Entry> entries = new ArrayList<Entry>();
for (Node child : asIterable(node.getChildNodes())) {
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
entries.add(new XMPEntry(child.getNamespaceURI() + child.getLocalName(), child.getLocalName(), getChildTextValue(child)));
}
return new RDFDescription(entries);
} | 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 cors() {
InputStream is = getClass().getResourceAsStream("/allow-origin4.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
for (boolean strict : new boolean[] {true, false}) {
assertTrue(restrictor.isOriginAllowed("http://bla.com", strict));
assertFalse(restrictor.isOriginAllowed("http://www.jolokia.org", strict));
assertTrue(restrictor.isOriginAllowed("https://www.consol.de", strict));
}
} | 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 handle(HttpServletRequest request, final HttpServletResponse response)
throws Exception
{
// We're sending an XML response, so set the response content type to text/xml
response.setContentType("text/xml");
// Parse the incoming request as XML
SAXReader xmlReader = new SAXReader();
Document doc = xmlReader.read(request.getInputStream());
Element env = doc.getRootElement();
final List<PollRequest> polls = unmarshalRequests(env);
new ContextualHttpServletRequest(request)
{
@Override
public void process() throws Exception
{
for (PollRequest req : polls)
{
req.poll();
}
// Package up the response
marshalResponse(polls, response.getOutputStream());
}
}.run();
} | 0 | Java | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | vulnerable |
public OldIESwithCipher(BlockCipher baseCipher)
{
super(new OldIESEngine(new DHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
new PaddedBufferedBlockCipher(baseCipher)));
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
public void create_withThreadPool() throws Exception {
final QueuedThreadPool threadPool = new QueuedThreadPool(100);
final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
final Routes routes = mock(Routes.class);
when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool));
final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool);
embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);
embeddedServer.ignite("localhost", 8080, null, 0,0,0);
verify(jettyServerFactory, times(1)).create(threadPool);
verifyNoMoreInteractions(jettyServerFactory);
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
protected int addFileNames(String[] file) { // This appears to only be used by unit tests
for (int i = 0; file != null && i < file.length; i++) {
workUnitList.add(new WorkUnit(file[i]));
}
return size();
} | 0 | Java | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
void sendResetPasswordEmailRequest() throws Exception
{
when(this.referenceSerializer.serialize(this.userReference)).thenReturn("user:Foobar");
when(this.userProperties.getFirstName()).thenReturn("Foo");
when(this.userProperties.getLastName()).thenReturn("Bar");
AuthenticationResourceReference resourceReference =
new AuthenticationResourceReference(AuthenticationAction.RESET_PASSWORD);
String verificationCode = "foobar4242";
resourceReference.addParameter("u", "user:Foobar");
resourceReference.addParameter("v", verificationCode);
ExtendedURL firstExtendedURL =
new ExtendedURL(Arrays.asList("authenticate", "reset"), resourceReference.getParameters());
when(this.resourceReferenceSerializer.serialize(resourceReference)).thenReturn(firstExtendedURL);
when(this.urlNormalizer.normalize(firstExtendedURL)).thenReturn(
new ExtendedURL(Arrays.asList("xwiki", "authenticate", "reset"), resourceReference.getParameters())
);
XWikiURLFactory urlFactory = mock(XWikiURLFactory.class);
when(this.context.getURLFactory()).thenReturn(urlFactory);
when(urlFactory.getServerURL(this.context)).thenReturn(new URL("http://xwiki.org"));
InternetAddress email = new InternetAddress("[email protected]");
DefaultResetPasswordRequestResponse requestResponse =
new DefaultResetPasswordRequestResponse(this.userReference, email,
verificationCode);
this.resetPasswordManager.sendResetPasswordEmailRequest(requestResponse);
verify(this.resetPasswordMailSender).sendResetPasswordEmail("Foo Bar", email,
new URL("http://xwiki.org/xwiki/authenticate/reset?u=user%3AFoobar&v=foobar4242"));
} | 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 JpaSort andUnsafe(Direction direction, String... properties) {
Assert.notEmpty(properties, "Properties must not be null!");
List<Order> orders = new ArrayList<Order>();
for (Order order : this) {
orders.add(order);
}
for (String property : properties) {
orders.add(new JpaOrder(direction, property));
}
return new JpaSort(orders, direction, Collections.<Path<?, ?>> emptyList());
} | 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 |
protected abstract void store(ConfidentialKey key, byte[] payload) throws IOException;
/**
* Reverse operation of {@link #store(ConfidentialKey, byte[])}
*
* @return
* null the data has not been previously persisted, or if the data was tampered.
*/
protected abstract @CheckForNull byte[] load(ConfidentialKey key) throws IOException;
/**
* Works like {@link SecureRandom#nextBytes(byte[])}.
*
* This enables implementations to consult other entropy sources, if it's available.
*/
public abstract byte[] randomBytes(int size);
/**
* Retrieves the currently active singleton instance of {@link ConfidentialStore}.
*/
public static @Nonnull ConfidentialStore get() {
if (TEST!=null) return TEST.get();
return Jenkins.getInstance().getExtensionList(ConfidentialStore.class).get(0);
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private void populateAuthCacheInAllPeers(AuthorizationContext authContext) throws Throwable {
// send a GET request to the ExampleService factory to populate auth cache on each peer.
// since factory is not OWNER_SELECTION service, request goes to the specified node.
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peer.setAuthorizationContext(authContext);
// based on the role created in test, all users have access to ExampleService
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildStatsUri(peer, ExampleService.FACTORY_LINK)));
}
this.host.waitFor("Timeout waiting for correct auth cache state",
() -> checkCacheInAllPeers(authContext.getToken(), true));
} | 0 | Java | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | vulnerable |
public Response attachTaskFile(@PathParam("courseId") Long courseId, @PathParam("nodeId") String nodeId,
@Context HttpServletRequest request) {
ICourse course = CoursesWebService.loadCourse(courseId);
CourseEditorTreeNode parentNode = getParentNode(course, nodeId);
if(course == null) {
return Response.serverError().status(Status.NOT_FOUND).build();
}
if(parentNode == null) {
return Response.serverError().status(Status.NOT_FOUND).build();
} else if(!(parentNode.getCourseNode() instanceof TACourseNode)) {
return Response.serverError().status(Status.NOT_ACCEPTABLE).build();
}
if (!isAuthorEditor(course, request)) {
return Response.serverError().status(Status.UNAUTHORIZED).build();
}
InputStream in = null;
MultipartReader reader = null;
try {
reader = new MultipartReader(request);
String filename = reader.getValue("filename", "task");
String taskFolderPath = TACourseNode.getTaskFolderPathRelToFolderRoot(course, parentNode.getCourseNode());
VFSContainer taskFolder = VFSManager.olatRootContainer(taskFolderPath, null);
VFSLeaf singleFile = (VFSLeaf) taskFolder.resolve("/" + filename);
if (singleFile == null) {
singleFile = taskFolder.createChildLeaf("/" + filename);
}
File file = reader.getFile();
if(file != null) {
in = new FileInputStream(file);
OutputStream out = singleFile.getOutputStream(false);
IOUtils.copy(in, out);
IOUtils.closeQuietly(out);
} else {
return Response.status(Status.NOT_ACCEPTABLE).build();
}
} catch (Exception e) {
log.error("", e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
} finally {
MultipartReader.closeQuietly(reader);
IOUtils.closeQuietly(in);
}
return Response.ok().build();
} | 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 GCM()
{
super(new GCMBlockCipher(new AESFastEngine()));
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
public void testAddSelf() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add(headers);
} | 0 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
public boolean isDone() {
return done.isOn();
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public static Object readObject(XStream xStream, InputStream is) {
try(InputStreamReader isr = new InputStreamReader(is, ENCODING);) {
return xStream.fromXML(isr);
} catch (Exception e) {
throw new OLATRuntimeException(XStreamHelper.class,
"could not read Object from inputstream: " + is, 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 |
parse_io(ThreadContext context,
IRubyObject klazz,
IRubyObject data,
IRubyObject enc)
{
//int encoding = (int)enc.convertToInteger().getLongValue();
final Ruby runtime = context.runtime;
XmlSaxParserContext ctx = newInstance(runtime, (RubyClass) klazz);
ctx.initialize(runtime);
ctx.setIOInputSource(context, data, runtime.getNil());
return ctx;
} | 0 | Java | CWE-241 | Improper Handling of Unexpected Data Type | The software does not handle or incorrectly handles when a particular element is not the expected type, e.g. it expects a digit (0-9) but is provided with a letter (A-Z). | https://cwe.mitre.org/data/definitions/241.html | vulnerable |
public WorkflowSearcher(Map<String, Object> map, User user) {
schemeId = getStringValue("schemeId", map);
assignedTo = getStringValue("assignedTo", map);
createdBy = getStringValue("createdBy", map);
stepId = getStringValue("stepId", map);
keywords = getStringValue("keywords", map);
orderBy = getStringValue("orderBy", map);
orderBy= SQLUtil.sanitizeSortBy(orderBy);
show4all = getBooleanValue("show4all", map);
open = getBooleanValue("open", map);
closed = getBooleanValue("closed", map);
String daysOldstr = getStringValue("daysold", map);
if(UtilMethods.isSet(daysOldstr) && daysOldstr.matches("^\\d+$"))
daysOld = Integer.parseInt(daysOldstr);
this.user = user;
try {
page = Integer.parseInt((String) getStringValue("page", map));
} catch (Exception e) {
page = 0;
}
if (page < 0)
page = 0;
try {
count = Integer.parseInt((String) getStringValue("count", map));
} catch (Exception e) {
count = 20;
}
if (count < 0)
count = 20;
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
private void store_pubkey(File dbPath, String serverName, String pk)
{
ArrayList<String> lines = new ArrayList<String>();
File vncDir = new File(FileUtils.getVncHomeDir());
try {
if (dbPath.exists()) {
FileReader db = new FileReader(dbPath);
BufferedReader dbBuf = new BufferedReader(db);
String line;
while ((line = dbBuf.readLine())!=null) {
String fields[] = line.split("\\|");
if (fields.length==6)
if (!serverName.equals(fields[2]) && !pk.equals(fields[5]))
lines.add(line);
}
dbBuf.close();
}
} catch (IOException e) {
throw new AuthFailureException("Could not load known hosts database");
}
try {
if (!dbPath.exists())
dbPath.createNewFile();
FileWriter fw = new FileWriter(dbPath.getAbsolutePath(), false);
Iterator i = lines.iterator();
while (i.hasNext())
fw.write((String)i.next()+"\n");
fw.write("|g0|"+serverName+"|*|0|"+pk+"\n");
fw.close();
} catch (IOException e) {
vlog.error("Failed to store server certificate to known hosts database");
}
} | 1 | Java | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | safe |
private ModelAndView addGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String groupName = request.getParameter("groupName");
String groupComment = request.getParameter("groupComment");
if (groupComment == null) {
groupComment = "";
}
if (groupName != null && groupName.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group ID must not contain any HTML markup.");
}
if (groupComment != null && groupComment.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group comment must not contain any HTML markup.");
}
boolean hasGroup = false;
try {
hasGroup = m_groupRepository.groupExists(groupName);
} catch (Throwable e) {
throw new ServletException("Can't determine if group " + groupName + " already exists in groups.xml.", e);
}
if (hasGroup) {
return new ModelAndView("admin/userGroupView/groups/newGroup", "action", "redo");
} else {
WebGroup newGroup = new WebGroup();
newGroup.setName(groupName);
newGroup.setComments(groupComment);
return editGroup(request, newGroup);
}
} | 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 testGetAndRemove() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name2", "value2", "value3");
headers.add("name3", "value4", "value5", "value6");
assertThat(headers.getAndRemove("name1", "defaultvalue")).isEqualTo("value1");
assertThat(headers.getAndRemove("name2")).isEqualTo("value2");
assertThat(headers.getAndRemove("name2")).isNull();
assertThat(headers.getAllAndRemove("name3")).containsExactly("value4", "value5", "value6");
assertThat(headers.size()).isZero();
assertThat(headers.getAndRemove("noname")).isNull();
assertThat(headers.getAndRemove("noname", "defaultvalue")).isEqualTo("defaultvalue");
} | 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 SpotProtocolDecoder(Protocol protocol) {
super(protocol);
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
builderFactory.setXIncludeAware(false);
builderFactory.setExpandEntityReferences(false);
documentBuilder = builderFactory.newDocumentBuilder();
xPath = XPathFactory.newInstance().newXPath();
messageExpression = xPath.compile("//messageList/message");
} catch (ParserConfigurationException | XPathExpressionException e) {
throw new RuntimeException(e);
}
} | 1 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | safe |
public MultiMap add(String name, String value) {
HttpUtils.validateHeader(name, value);
headers.add(toLowerCase(name), value);
return this;
} | 1 | Java | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
byte[] ciphertext, int ciphertextOffset, int length)
throws ShortBufferException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (keySpec == null) {
// The key is not set yet - return the plaintext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
return length;
}
if (space < 16 || length > (space - 16))
throw new ShortBufferException();
try {
setup(ad);
int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);
cipher.doFinal(ciphertext, ciphertextOffset + result);
} catch (InvalidKeyException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (InvalidAlgorithmParameterException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (IllegalBlockSizeException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (BadPaddingException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
ghash.update(ciphertext, ciphertextOffset, length);
ghash.pad(ad != null ? ad.length : 0, length);
ghash.finish(ciphertext, ciphertextOffset + length, 16);
for (int index = 0; index < 16; ++index)
ciphertext[ciphertextOffset + length + index] ^= hashKey[index];
return length + 16;
} | 0 | Java | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
public AbstractXmlConfigRootTagRecognizer(String expectedRootNode) throws Exception {
this.expectedRootNode = expectedRootNode;
SAXParserFactory factory = SAXParserFactory.newInstance();
saxParser = factory.newSAXParser();
} | 0 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | vulnerable |
public String getEncryptedValue() {
try {
Cipher cipher = getCipher("AES");
cipher.init(Cipher.ENCRYPT_MODE, getKey());
// add the magic suffix which works like a check sum.
return new String(Base64.encode(cipher.doFinal((value+MAGIC).getBytes("UTF-8"))));
} catch (GeneralSecurityException e) {
throw new Error(e); // impossible
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public void setProperty(String name, Object value) throws SAXException {
getXMLReader().setProperty(name, value);
} | 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 Document read(InputStream in) throws DocumentException {
InputSource source = new InputSource(in);
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 |
private String getLocalePrefix(FacesContext context) {
String localePrefix = null;
localePrefix = context.getExternalContext().getRequestParameterMap().get("loc");
if(localePrefix != null && !nameContainsForbiddenSequence(localePrefix)){
return localePrefix;
} else {
localePrefix = null;
}
String appBundleName = context.getApplication().getMessageBundle();
if (null != appBundleName) {
Locale locale = null;
if (context.getViewRoot() != null) {
locale = context.getViewRoot().getLocale();
} else {
locale = context.getApplication().getViewHandler().calculateLocale(context);
}
try {
ResourceBundle appBundle =
ResourceBundle.getBundle(appBundleName,
locale,
Util.getCurrentLoader(ResourceManager.class));
localePrefix =
appBundle
.getString(ResourceHandler.LOCALE_PREFIX);
} catch (MissingResourceException mre) {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "Ignoring missing resource", mre);
}
}
}
return localePrefix;
} | 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 static void assertQueryStringAllowed(String rawPath, String expectedQuery) {
final PathAndQuery res = parse(rawPath);
assertThat(res)
.as("parse(\"%s\") must return non-null.", rawPath)
.isNotNull();
assertThat(res.query())
.as("parse(\"%s\").query() must return \"%s\".", rawPath, expectedQuery)
.isEqualTo(expectedQuery);
} | 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 translate(MobEquipmentPacket packet, GeyserSession session) {
if (!session.isSpawned() || packet.getHotbarSlot() > 8 ||
packet.getContainerId() != ContainerId.INVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) {
// For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention
return;
}
// Send book update before switching hotbar slot
session.getBookEditCache().checkForSend();
session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot());
ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot());
session.sendDownstreamPacket(changeHeldItemPacket);
if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {
// Activate shield since we are already sneaking
// (No need to send a release item packet - Java doesn't do this when swapping items)
// Required to do it a tick later or else it doesn't register
session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)),
50, TimeUnit.MILLISECONDS);
}
// Java sends a cooldown indicator whenever you switch an item
CooldownUtils.sendCooldown(session);
// Update the interactive tag, if an entity is present
if (session.getMouseoverEntity() != null) {
InteractiveTagManager.updateTag(session, session.getMouseoverEntity());
}
} | 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 AuthorizationCodeRequestUrl newAuthorizationUrl() {
return new AuthorizationCodeRequestUrl(authorizationServerEncodedUrl, clientId).setScopes(
scopes);
} | 0 | Java | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
protected void init(final Form< ? > form)
{
this.form = form;
csrfTokenHandler = new CsrfTokenHandler(form);
mainSubContainer.add(form);
form.add(gridContentContainer);
form.add(buttonBarContainer);
if (showCancelButton == true) {
final SingleButtonPanel cancelButton = appendNewAjaxActionButton(new AjaxCallback() {
@Override
public void callback(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
onCancelButtonSubmit(target);
close(target);
}
}, getString("cancel"), SingleButtonPanel.CANCEL);
cancelButton.getButton().setDefaultFormProcessing(false);
}
closeButtonPanel = appendNewAjaxActionButton(new AjaxFormSubmitCallback() {
@Override
public void callback(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
if (onCloseButtonSubmit(target)) {
close(target);
}
}
@Override
public void onError(final AjaxRequestTarget target, final Form< ? > form)
{
csrfTokenHandler.onSubmit();
ModalDialog.this.onError(target, form);
}
}, closeButtonLabel != null ? closeButtonLabel : getString("close"), SingleButtonPanel.NORMAL);
buttonBarContainer.add(actionButtons.getRepeatingView());
form.setDefaultButton(closeButtonPanel.getButton());
if (autoGenerateGridBuilder == true) {
gridBuilder = new GridBuilder(gridContentContainer, "flowform");
}
initFeedback(gridContentContainer);
} | 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 translate(ServerPlayerSetExperiencePacket packet, GeyserSession session) {
SessionPlayerEntity entity = session.getPlayerEntity();
AttributeData experience = GeyserAttributeType.EXPERIENCE.getAttribute(packet.getExperience());
entity.getAttributes().put(GeyserAttributeType.EXPERIENCE, experience);
AttributeData experienceLevel = GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(packet.getLevel());
entity.getAttributes().put(GeyserAttributeType.EXPERIENCE_LEVEL, experienceLevel);
UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());
attributesPacket.setAttributes(Arrays.asList(experience, experienceLevel));
session.sendUpstreamPacket(attributesPacket);
} | 0 | Java | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
public static String getAttachedFilePath(String inputStudyOid) {
// Using a standard library to validate/Sanitize user inputs which will be used in path expression to prevent from path traversal
String studyOid = FilenameUtils.getName(inputStudyOid);
String attachedFilePath = CoreResources.getField("attached_file_location");
if (attachedFilePath == null || attachedFilePath.length() <= 0) {
attachedFilePath = CoreResources.getField("filePath") + "attached_files" + File.separator + studyOid + File.separator;
} else {
attachedFilePath += studyOid + File.separator;
}
return attachedFilePath;
} | 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 add0(int h, int i, AsciiString name, String value) {
validateValue(value);
// Update the hash table.
entries[i] = new HeaderEntry(h, name, value, entries[i]);
++size;
} | 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 emptyHeadersShouldBeEqual() {
final HttpHeadersBase headers1 = newEmptyHeaders();
final HttpHeadersBase headers2 = newEmptyHeaders();
assertThat(headers2).isEqualTo(headers1);
assertThat(headers2.hashCode()).isEqualTo(headers1.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 testSetContentFromFile() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf = test.getByteBuf();
assertEquals(buf.readerIndex(), 0);
assertEquals(buf.writerIndex(), bytes.length);
assertArrayEquals(bytes, test.get());
assertArrayEquals(bytes, ByteBufUtil.getBytes(buf));
} finally {
//release the ByteBuf
test.delete();
}
} | 0 | Java | CWE-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 |
protected Key engineDoPhase(
Key key,
boolean lastPhase)
throws InvalidKeyException, IllegalStateException
{
if (x == null)
{
throw new IllegalStateException("Diffie-Hellman not initialised.");
}
if (!(key instanceof DHPublicKey))
{
throw new InvalidKeyException("DHKeyAgreement doPhase requires DHPublicKey");
}
DHPublicKey pubKey = (DHPublicKey)key;
if (!pubKey.getParams().getG().equals(g) || !pubKey.getParams().getP().equals(p))
{
throw new InvalidKeyException("DHPublicKey not for this KeyAgreement!");
}
BigInteger peerY = ((DHPublicKey)key).getY();
if (peerY == null || peerY.compareTo(TWO) < 0
|| peerY.compareTo(p.subtract(ONE)) >= 0)
{
throw new InvalidKeyException("Invalid DH PublicKey");
}
result = peerY.modPow(x, p);
if (result.compareTo(ONE) == 0)
{
throw new InvalidKeyException("Shared key can't be 1");
}
if (lastPhase)
{
return null;
}
return new BCDHPublicKey(result, pubKey.getParams());
} | 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 |
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
} | 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 byte[] toByteArray()
{
/* index || secretKeySeed || secretKeyPRF || publicSeed || root */
int n = params.getDigestSize();
int indexSize = (params.getHeight() + 7) / 8;
int secretKeySize = n;
int secretKeyPRFSize = n;
int publicSeedSize = n;
int rootSize = n;
int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize;
byte[] out = new byte[totalSize];
int position = 0;
/* copy index */
byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize);
XMSSUtil.copyBytesAtOffset(out, indexBytes, position);
position += indexSize;
/* copy secretKeySeed */
XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position);
position += secretKeySize;
/* copy secretKeyPRF */
XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position);
position += secretKeyPRFSize;
/* copy publicSeed */
XMSSUtil.copyBytesAtOffset(out, publicSeed, position);
position += publicSeedSize;
/* copy root */
XMSSUtil.copyBytesAtOffset(out, root, position);
/* concatenate bdsState */
byte[] bdsStateOut = null;
try
{
bdsStateOut = XMSSUtil.serialize(bdsState);
}
catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("error serializing bds state");
}
return Arrays.concatenate(out, bdsStateOut);
} | 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 |
private File getFileFor(ConfidentialKey key) {
return new File(rootDir, key.getId());
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void test_notLike_startsWith() {
Entity from = from(Entity.class);
where(from.getCode()).notLike().startsWith("test");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where entity_0.code not like :code_1", select.getQuery());
assertEquals("test%", select.getParameters().get("code_1"));
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void translate(CommandRequestPacket packet, GeyserSession session) {
String command = packet.getCommand().replace("/", "");
CommandManager commandManager = GeyserConnector.getInstance().getCommandManager();
if (session.getConnector().getPlatformType() == PlatformType.STANDALONE && command.trim().startsWith("geyser ") && commandManager.getCommands().containsKey(command.split(" ")[1])) {
commandManager.runCommand(session, command);
} else {
String message = packet.getCommand().trim();
if (MessageTranslator.isTooLong(message, session)) {
return;
}
ClientChatPacket chatPacket = new ClientChatPacket(message);
session.sendDownstreamPacket(chatPacket);
}
} | 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 boolean isResetPasswordSent()
{
// If there is no form and we see an info box, then the request was sent.
return !getDriver().hasElementWithoutWaiting(By.cssSelector("#resetPasswordForm"))
&& messageBox.getText().contains("An e-mail was sent to");
} | 0 | Java | CWE-640 | Weak Password Recovery Mechanism for Forgotten Password | The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak. | https://cwe.mitre.org/data/definitions/640.html | vulnerable |
public void testHeaderNameStartsWithControlChar1d() {
testHeaderNameStartsWithControlChar(0x1d);
} | 1 | Java | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
void emptyHeadersShouldBeEqual() {
final HttpHeadersBase headers1 = newEmptyHeaders();
final HttpHeadersBase headers2 = newEmptyHeaders();
assertThat(headers2).isEqualTo(headers1);
assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode());
} | 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 PBEWithSHA1AESCBC192()
{
super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 192, 16);
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
public void subValidateFail(ViolationCollector col) {
col.addViolation(FAILED+"subclass");
} | 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 String getPasswordValue(Object o) {
if (o==null) return null;
if (o instanceof Secret) return ((Secret)o).getEncryptedValue();
if (getIsUnitTest()) {
throw new SecurityException("attempted to render plaintext ‘" + o + "’ in password field; use a getter of type Secret instead");
}
return o.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 |
protected String getCorsDomain(String referer, String userAgent)
{
String dom = null;
if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".draw.io/") + 8);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".diagrams.net/") + 13);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".quipelements.com/") + 17);
}
// Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions)
// UA refers to old FF on macOS so low risk and fixes requests from existing servers
else if ((referer != null
&& referer.equals("draw.io Proxy Confluence Server"))
|| (userAgent != null && userAgent.equals(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0")))
{
dom = "";
}
return dom;
} | 0 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
public byte[] decrypt(final JWEHeader header,
final Base64URL encryptedKey,
final Base64URL iv,
final Base64URL cipherText,
final Base64URL authTag)
throws JOSEException {
final JWEAlgorithm alg = header.getAlgorithm();
final ECDH.AlgorithmMode algMode = ECDH.resolveAlgorithmMode(alg);
critPolicy.ensureHeaderPasses(header);
// Get ephemeral EC key
ECKey ephemeralKey = header.getEphemeralPublicKey();
if (ephemeralKey == null) {
throw new JOSEException("Missing ephemeral public EC key \"epk\" JWE header parameter");
}
ECPublicKey ephemeralPublicKey = ephemeralKey.toECPublicKey();
// Curve check
ECDH.ensurePointOnCurve(ephemeralPublicKey, getPrivateKey());
// Derive 'Z'
SecretKey Z = ECDH.deriveSharedSecret(
ephemeralPublicKey,
privateKey,
getJCAContext().getKeyEncryptionProvider());
// Derive shared key via concat KDF
getConcatKDF().getJCAContext().setProvider(getJCAContext().getMACProvider()); // update before concat
SecretKey sharedKey = ECDH.deriveSharedKey(header, Z, getConcatKDF());
final SecretKey cek;
if (algMode.equals(ECDH.AlgorithmMode.DIRECT)) {
cek = sharedKey;
} else if (algMode.equals(ECDH.AlgorithmMode.KW)) {
if (encryptedKey == null) {
throw new JOSEException("Missing JWE encrypted key");
}
cek = AESKW.unwrapCEK(sharedKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider());
} else {
throw new JOSEException("Unexpected JWE ECDH algorithm mode: " + algMode);
}
return ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext());
} | 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 checkAccess(Thread t) {
if (RobocodeProperties.isSecurityOff()) {
return;
}
Thread c = Thread.currentThread();
if (isSafeThread(c)) {
return;
}
super.checkAccess(t);
// Threads belonging to other thread groups is not allowed to access threads belonging to other thread groups
// Bug fix [3021140] Possible for robot to kill other robot threads.
// In the following the thread group of the current thread must be in the thread group hierarchy of the
// attacker thread; otherwise an AccessControlException must be thrown.
boolean found = false;
ThreadGroup cg = c.getThreadGroup();
ThreadGroup tg = t.getThreadGroup();
while (tg != null) {
if (tg == cg) {
found = true;
break;
}
try {
tg = tg.getParent();
} catch (AccessControlException e) {
// We expect an AccessControlException due to missing RuntimePermission modifyThreadGroup
break;
}
}
if (!found) {
String message = "Preventing " + c.getName() + " from access to " + t.getName();
IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);
if (robotProxy != null) {
robotProxy.punishSecurityViolation(message);
}
throw new SecurityException(message);
}
} | 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 |
void colon() {
assertThat(PathAndQuery.parse("/:")).isNotNull();
assertThat(PathAndQuery.parse("/:/")).isNotNull();
assertThat(PathAndQuery.parse("/a/:")).isNotNull();
assertThat(PathAndQuery.parse("/a/:/")).isNotNull();
} | 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 void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null) {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject == null) {
Helpers.doForbidden(response);
return;
}
session = request.getSession(true);
session.setAttribute("subject", subject);
} else {
Subject subject = (Subject) session.getAttribute("subject");
if (subject == null) {
session.invalidate();
Helpers.doForbidden(response);
return;
}
}
String encoding = request.getHeader("Accept-Encoding");
boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
SessionTerminal st = (SessionTerminal) session.getAttribute("terminal");
if (st == null || st.isClosed()) {
st = new SessionTerminal(getCommandProcessor(), getThreadIO());
session.setAttribute("terminal", st);
}
String str = request.getParameter("k");
String f = request.getParameter("f");
String dump = st.handle(str, f != null && f.length() > 0);
if (dump != null) {
if (supportsGzip) {
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Type", "text/html");
try {
GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
gzos.write(dump.getBytes());
gzos.close();
} catch (IOException ie) {
LOG.info("Exception writing response: ", ie);
}
} else {
response.getOutputStream().write(dump.getBytes());
}
}
} | 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 static void testSetCompact() throws Exception {
TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding);
TProtocol iprot = new TCompactProtocol(buf);
testTruncated(new MySetStruct(), iprot);
} | 1 | Java | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
public void testHeaderNameStartsWithControlChar1c() {
testHeaderNameStartsWithControlChar(0x1c);
} | 1 | Java | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
public void testCurveMismatch()
throws Exception {
// EC key on P_256
ECParameterSpec ecParameterSpec = ECKey.Curve.P_256.toECParameterSpec();
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
generator.initialize(ecParameterSpec);
KeyPair keyPair = generator.generateKeyPair();
ECKey ecJWK_p256 = new ECKey.Builder(ECKey.Curve.P_256, (ECPublicKey) keyPair.getPublic())
.privateKey((ECPrivateKey) keyPair.getPrivate())
.build();
// EC key on P_384
ecParameterSpec = ECKey.Curve.P_384.toECParameterSpec();
generator = KeyPairGenerator.getInstance("EC");
generator.initialize(ecParameterSpec);
keyPair = generator.generateKeyPair();
ECKey ecJWK_p384 = new ECKey.Builder(ECKey.Curve.P_384, (ECPublicKey) keyPair.getPublic())
.privateKey((ECPrivateKey) keyPair.getPrivate())
.build();
// Try to create EC key with P_256 params, but with x and y from P_384 curve key
ECPoint w = new ECPoint(ecJWK_p384.getX().decodeToBigInteger(), ecJWK_p384.getY().decodeToBigInteger());
ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(w, ECKey.Curve.P_256.toECParameterSpec());
// Default Sun provider
try {
KeyFactory keyFactory = KeyFactory.getInstance("EC");
keyFactory.generatePublic(publicKeySpec);
fail();
} catch (RuntimeException e) {
assertEquals("Point coordinates do not match field size", e.getMessage());
}
// BouncyCastle provider
try {
KeyFactory keyFactory = KeyFactory.getInstance("EC", BouncyCastleProviderSingleton.getInstance());
keyFactory.generatePublic(publicKeySpec);
fail();
} catch (InvalidKeySpecException e) {
assertEquals("invalid KeySpec: x value invalid for SecP256R1FieldElement", e.getMessage());
}
} | 1 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | safe |
public Cipher decrypt() {
try {
Cipher cipher = Secret.getCipher(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getKey());
return cipher;
} catch (GeneralSecurityException e) {
throw new AssertionError(e);
}
} | 1 | Java | CWE-326 | Inadequate Encryption Strength | The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required. | https://cwe.mitre.org/data/definitions/326.html | safe |
static DataSource lookupDataSource(Hints hints) throws FactoryException {
Object hint = hints.get(Hints.EPSG_DATA_SOURCE);
if (hint instanceof DataSource) {
return (DataSource) hint;
} else if (hint instanceof String) {
String name = (String) hint;
InitialContext context;
try {
context = GeoTools.getInitialContext();
// name = GeoTools.fixName( context, name );
return (DataSource) context.lookup(name);
} catch (Exception e) {
throw new FactoryException("EPSG_DATA_SOURCE '" + name + "' not found:" + e, e);
}
}
throw new FactoryException("EPSG_DATA_SOURCE must be provided");
} | 0 | Java | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
private static Stream<Arguments> provideFilesAndExpectedExceptionType() {
return Stream.of(
Arguments.of("abnormal/corrupt-header.rar", CorruptHeaderException.class),
Arguments.of("abnormal/mainHeaderNull.rar", BadRarArchiveException.class),
Arguments.of("abnormal/loop.rar", CorruptHeaderException.class)
);
} | 1 | Java | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
protected Map<String, Serializable> getPrincipal(Jwt jwt) {
Map<String, Serializable> principal = new HashMap<>();
principal.put("jwt", (Serializable) jwt.getBody());
return principal;
} | 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 static String getRealIp(HttpServletRequest request) {
//bae env
if (ZrLogUtil.isBae() && request.getHeader("clientip") != null) {
return request.getHeader("clientip");
}
String ip = request.getHeader("X-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
} | 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 ECIESwithAES()
{
super(new AESEngine());
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
Randoms() {
random = new Random();
Date date = new Date();
random.setSeed(date.getTime());
} | 0 | Java | CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information. | https://cwe.mitre.org/data/definitions/327.html | vulnerable |
protected void before() throws Throwable {
byte[] random = new byte[32];
sr.nextBytes(random);
value = Util.toHexString(random);
Secret.SECRET = value;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void addViolation(String propertyName, Integer index, String message) {
addViolation(propertyName, index, message, Collections.emptyMap());
} | 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 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 void headerMultipleContentLengthValidationShouldPropagate() {
headerMultipleContentLengthValidationShouldPropagate(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 void writeFile( Path path,
FileItem uploadedItem ) throws IOException {
if ( !ioService.exists( path ) ) {
ioService.createFile( path );
}
ioService.write( path, IOUtils.toByteArray( uploadedItem.getInputStream() ) );
uploadedItem.getInputStream().close();
} | 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 UserCause(@CheckForNull User user, @CheckForNull String message) {
this(
user != null ? user.getId() : null,
message != null ? " : " + message : ""
);
} | 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 test_notLike_endsWith() {
Entity from = from(Entity.class);
where(from.getCode()).notLike().endsWith("test");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where entity_0.code not like '%test'", select.getQuery());
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public IESParameterSpec(
byte[] derivation,
byte[] encoding,
int macKeySize,
int cipherKeySize)
{
this(derivation, encoding, macKeySize, cipherKeySize, null, false);
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
public void 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 testReadBytesAndWriteBytesWithFileChannel() throws IOException {
File file = File.createTempFile("file-channel", ".tmp");
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel();
// channelPosition should never be changed
long channelPosition = channel.position();
byte[] bytes = {'a', 'b', 'c', 'd'};
int len = bytes.length;
ByteBuf buffer = newBuffer(len);
buffer.resetReaderIndex();
buffer.resetWriterIndex();
buffer.writeBytes(bytes);
int oldReaderIndex = buffer.readerIndex();
assertEquals(len, buffer.readBytes(channel, 10, len));
assertEquals(oldReaderIndex + len, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(len, buffer2.writeBytes(channel, 10, len));
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex + len, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(0));
assertEquals('b', buffer2.getByte(1));
assertEquals('c', buffer2.getByte(2));
assertEquals('d', buffer2.getByte(3));
buffer.release();
buffer2.release();
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
file.delete();
}
} | 0 | Java | CWE-378 | Creation of Temporary File With Insecure Permissions | Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack. | https://cwe.mitre.org/data/definitions/378.html | vulnerable |
protected void store(byte[] payload) throws IOException {
ConfidentialStore.get().store(this,payload);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
protected int typeMinimumSize(byte type) {
switch (type & 0x0f) {
case TType.BOOL:
case TType.BYTE:
case TType.I16: // because of variable length encoding
case TType.I32: // because of variable length encoding
case TType.I64: // because of variable length encoding
return 1;
case TType.FLOAT:
return 4;
case TType.DOUBLE:
return 8;
case TType.STRING:
case TType.STRUCT:
case TType.MAP:
case TType.SET:
case TType.LIST:
case TType.ENUM:
return 1;
default:
throw new TProtocolException(
TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f));
}
} | 1 | Java | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
public void create_withNullThreadPool() throws Exception {
final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
final Routes routes = mock(Routes.class);
when(jettyServerFactory.create(100, 10, 10000)).thenReturn(new Server());
final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null);
embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);
embeddedServer.ignite("localhost", 6759, 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 checkInvalidCallback(boolean streaming) throws URISyntaxException, IOException, ParseException {
JolokiaHttpHandler handler = new JolokiaHttpHandler(getConfig(ConfigKey.SERIALIZE_EXCEPTION, Boolean.toString(streaming)));
handler.start(false);
HttpExchange exchange = prepareExchange("http://localhost:8080/jolokia/read/java.lang:type=Memory/HeapMemoryUsage?callback=evilCallback();data");
// Simple GET method
expect(exchange.getRequestMethod()).andReturn("GET");
Headers header = new Headers();
ByteArrayOutputStream out = prepareResponse(handler, exchange, header);
handler.doHandle(exchange);
assertEquals(header.getFirst("content-type"),"text/plain; charset=utf-8");
String result = out.toString("utf-8");
JSONObject resp = (JSONObject) new JSONParser().parse(result);
assertTrue(resp.containsKey("error"));
assertEquals(resp.get("error_type"), IllegalArgumentException.class.getName());
assertTrue(((String) resp.get("error")).contains("callback"));
assertFalse(((String) resp.get("error")).contains("evilCallback"));
handler.stop();
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
public static String htmlEscape(String text) {
StringBuilder buf = new StringBuilder(text.length()+64);
for( int i=0; i<text.length(); i++ ) {
char ch = text.charAt(i);
if(ch=='<')
buf.append("<");
else
if(ch=='&')
buf.append("&");
else
buf.append(ch);
}
return buf.toString();
} | 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 JpaOrder with(Direction order) {
return new JpaOrder(order, getProperty(), getNullHandling(), isIgnoreCase(), this.unsafe);
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
public void doHeapDump(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException {
owner.checkPermission(Jenkins.ADMINISTER);
rsp.setContentType("application/octet-stream");
FilePath dump = obtain();
try {
dump.copyTo(rsp.getCompressedOutputStream(req));
} finally {
dump.delete();
}
} | 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 |
final void setObject(CharSequence name, Iterable<?> values) {
final AsciiString normalizedName = HttpHeaderNames.of(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));
}
} | 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 normalizeName(CharSequence name) {
checkArgument(requireNonNull(name, "name").length() > 0, "name is empty.");
return HttpHeaderNames.of(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 static IRubyObject from_document(ThreadContext context, IRubyObject klazz, IRubyObject document) {
XmlDocument doc = ((XmlDocument) ((XmlNode) document).document(context));
RubyArray errors = (RubyArray) doc.getInstanceVariable("@errors");
if (!errors.isEmpty()) {
throw ((XmlSyntaxError) errors.first()).toThrowable();
}
DOMSource source = new DOMSource(doc.getDocument());
IRubyObject uri = doc.url(context);
if (!uri.isNil()) {
source.setSystemId(uri.convertToString().asJavaString());
}
return getSchema(context, (RubyClass)klazz, 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 |
void plus() {
final PathAndQuery res = PathAndQuery.parse("/+?a+b=c+d");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/+");
assertThat(res.query()).isEqualTo("a+b=c+d");
final PathAndQuery res2 = PathAndQuery.parse("/%2b?a%2bb=c%2bd");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/+");
assertThat(res2.query()).isEqualTo("a%2Bb=c%2Bd");
} | 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 Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) {
setTranslator(trans);
currentContainer = folderComponent.getCurrentContainer();
if (currentContainer.canWrite() != VFSConstants.YES) {
throw new AssertException("Cannot write to current folder.");
}
status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
if(status == FolderCommandStatus.STATUS_FAILED) {
return null;
}
selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
if(status == FolderCommandStatus.STATUS_FAILED) {
return null;
}
if(selection.getFiles().isEmpty()) {
status = FolderCommandStatus.STATUS_FAILED;
wControl.setWarning(trans.translate("warning.file.selection.empty"));
return null;
}
initForm(ureq);
return this;
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (!haskey) {
// The key is not set yet - return the plaintext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
return length;
}
if (space < 16 || length > (space - 16))
throw new ShortBufferException();
setup(ad);
encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
poly.update(ciphertext, ciphertextOffset, length);
finish(ad, length);
System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16);
return length + 16;
} | 0 | Java | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
private byte[] verifyMagic(byte[] payload) {
int payloadLen = payload.length-MAGIC.length;
if (payloadLen<0) return null; // obviously broken
for (int i=0; i<MAGIC.length; i++) {
if (payload[payloadLen+i]!=MAGIC[i])
return null; // broken
}
byte[] truncated = new byte[payloadLen];
System.arraycopy(payload,0,truncated,0,truncated.length);
return truncated;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void doubleQuote() {
final PathAndQuery res = PathAndQuery.parse("/\"?\"");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/%22");
assertThat(res.query()).isEqualTo("%22");
} | 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 destroy() {
if (_configuration == null) {
return;
}
_classLoaderHelperUtilities.clear();
_classLoaderHelperUtilities = null;
_configuration.clearEncodingMap();
_configuration.clearSharedVariables();
_configuration.clearTemplateCache();
_configuration = null;
_restrictedHelperUtilities.clear();
_restrictedHelperUtilities = null;
_standardHelperUtilities.clear();
_standardHelperUtilities = null;
_stringTemplateLoader.removeTemplates();
_stringTemplateLoader = null;
_templateContextHelper = null;
} | 1 | Java | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
private PropPatchParseResult parseContent( byte[] arr ) throws IOException, SAXException {
if( arr.length > 0 ) {
log.debug( "processing content" );
ByteArrayInputStream bin = new ByteArrayInputStream( arr );
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
// https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
PropPatchSaxHandler handler = new PropPatchSaxHandler();
reader.setContentHandler( handler );
reader.parse( new InputSource( bin ) );
log.debug( "toset: " + handler.getAttributesToSet().size());
return new PropPatchParseResult( handler.getAttributesToSet(), handler.getAttributesToRemove().keySet() );
} else {
log.debug( "empty content" );
return new PropPatchParseResult( new HashMap<QName, String>(), new HashSet<QName>() );
}
}
| 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 static AsciiString validate(AsciiString name) {
if (name.isEmpty()) {
throw new IllegalArgumentException("malformed header name: <EMPTY>");
}
final int lastIndex;
try {
lastIndex = name.forEachByte(value -> {
if ((value & PROHIBITED_NAME_CHAR_MASK) != 0) { // value >= 64
return true;
}
// value < 64
return !PROHIBITED_NAME_CHARS.get(value);
});
} catch (Exception e) {
throw new Error(e);
}
if (lastIndex >= 0) {
throw new IllegalArgumentException(malformedHeaderNameMessage(name));
}
return name;
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
protected Response newBrowserAuthentication(AuthenticationSessionModel authSession, boolean isPassive, boolean redirectToAuthentication, SamlProtocol samlProtocol) {
// Saml ECP flow creates only TRANSIENT user sessions
authSession.setClientNote(AuthenticationManager.USER_SESSION_PERSISTENT_STATE, UserSessionModel.SessionPersistenceState.TRANSIENT.toString());
return super.newBrowserAuthentication(authSession, isPassive, redirectToAuthentication, createEcpSamlProtocol());
} | 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 |
protected void sendResponse(HttpSession session, Subject subject, PrintWriter out) {
String token = (String) session.getAttribute(LOGIN_TOKEN);
if ( token == null) {
byte[] seed = (subject.toString() + new Long(System.currentTimeMillis()).toString()).getBytes();
SecureRandom random = new SecureRandom(seed);
byte[] tokenBytes = new byte[128];
random.nextBytes(tokenBytes);
token = Base64.encodeBase64String(tokenBytes);
session.setAttribute(LOGIN_TOKEN, token);
}
Map<String, String> answer = new HashMap<String, String>();
answer.put("token", token);
ServletHelpers.writeObject(converters, options, out, answer);
} | 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 existingDocumentFromUINoName() 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);
// Just landed on the create page or submitted with no values (no name) specified.
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify that the create template is rendered, so the UI is displayed for the user to enter the missing values.
assertEquals("create", result);
// We should not get this far so no redirect should be done, just the template will be rendered.
verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),
any(), any(XWikiContext.class));
} | 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 ECIESwithCipher(BlockCipher cipher)
{
super(new IESEngine(new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
new PaddedBufferedBlockCipher(cipher)));
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
byte[] ciphertext, int ciphertextOffset, int length)
throws ShortBufferException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (keySpec == null) {
// The key is not set yet - return the plaintext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
return length;
}
if (space < 16 || length > (space - 16))
throw new ShortBufferException();
try {
setup(ad);
int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);
cipher.doFinal(ciphertext, ciphertextOffset + result);
} catch (InvalidKeyException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (InvalidAlgorithmParameterException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (IllegalBlockSizeException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (BadPaddingException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
ghash.update(ciphertext, ciphertextOffset, length);
ghash.pad(ad != null ? ad.length : 0, length);
ghash.finish(ciphertext, ciphertextOffset + length, 16);
for (int index = 0; index < 16; ++index)
ciphertext[ciphertextOffset + length + index] ^= hashKey[index];
return length + 16;
} | 0 | Java | CWE-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.