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 void newDocumentFromURLTemplateProviderSpecifiedButNotAllowed() throws Exception
{
// new document = xwiki:X.Y
DocumentReference documentReference =
new DocumentReference("Y", new SpaceReference("X", new WikiReference("xwiki")));
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"),
Arrays.asList("AnythingButX"));
// 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 see the error.
assertEquals("create", result);
// Check that the exception is properly set in the context for the UI to display.
XWikiException exception = (XWikiException) this.oldcore.getScriptContext().getAttribute("createException");
assertNotNull(exception);
assertEquals(XWikiException.ERROR_XWIKI_APP_TEMPLATE_NOT_AVAILABLE, exception.getCode());
// 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 void translate(ServerDifficultyPacket packet, GeyserSession session) {
SetDifficultyPacket setDifficultyPacket = new SetDifficultyPacket();
setDifficultyPacket.setDifficulty(packet.getDifficulty().ordinal());
session.sendUpstreamPacket(setDifficultyPacket);
session.getWorldCache().setDifficulty(packet.getDifficulty());
} | 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 existingDocumentFromUITemplateProviderSpecifiedRestrictionExistsOnParentSpace() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Submit from the UI spaceReference=X.Y.Z&name=W&templateProvider=XWiki.MyTemplateProvider
String templateProviderFullName = "XWiki.MyTemplateProvider";
String spaceReferenceString = "X.Y.Z";
when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString);
when(mockRequest.getParameter("name")).thenReturn("W");
when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);
// Mock 1 existing template provider that allows usage in one of the target space's parents (top level in this
// case).
mockExistingTemplateProviders(templateProviderFullName,
new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Arrays.asList("X"));
// 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);
// Note1: We are allowed to create anything under space X or its children, be it a terminal or a non-terminal
// document
// Note2: We are creating X.Y.Z.W and using the template extracted from the template provider.
verify(mockURLFactory).createURL("X.Y.Z.W", "WebHome", "edit",
"template=XWiki.MyTemplate&parent=Main.WebHome&title=W", 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 |
protected void run() {
URL busFile = HostnameVerificationDeprecatedServer.class.getResource("hostname-server-bethal.xml");
Bus busLocal = new SpringBusFactory().createBus(busFile);
BusFactory.setDefaultBus(busLocal);
setBus(busLocal);
try {
new HostnameVerificationDeprecatedServer();
} catch (Exception e) {
e.printStackTrace();
}
} | 1 | Java | CWE-755 | Improper Handling of Exceptional Conditions | The software does not handle or incorrectly handles an exceptional condition. | https://cwe.mitre.org/data/definitions/755.html | safe |
public boolean matches(ConditionContext context) {
BeanContext beanContext = context.getBeanContext();
if (beanContext instanceof ApplicationContext) {
List<String> paths = ((ApplicationContext) beanContext)
.getEnvironment()
.getProperty(FileWatchConfiguration.PATHS, Argument.listOf(String.class))
.orElse(null);
if (CollectionUtils.isNotEmpty(paths)) {
boolean matchedPaths = paths.stream().anyMatch(p -> new File(p).exists());
if (!matchedPaths) {
context.fail("File watch disabled because no paths matching the watch pattern exist (Paths: " + paths + ")");
}
return matchedPaths;
}
}
context.fail("File watch disabled because no watch paths specified");
return false;
} | 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 void initWithCustomLogHandler() throws Exception {
servlet = new AgentServlet();
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
HttpTestUtil.prepareServletConfigMock(config, new String[]{ConfigKey.LOGHANDLER_CLASS.getKeyValue(), CustomLogHandler.class.getName()});
HttpTestUtil.prepareServletContextMock(context,null);
expect(config.getServletContext()).andReturn(context).anyTimes();
expect(config.getServletName()).andReturn("jolokia").anyTimes();
replay(config, context);
servlet.init(config);
servlet.destroy();
assertTrue(CustomLogHandler.infoCount > 0);
} | 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 |
protected void parseModuleConfigFile(Digester digester, String path)
throws UnavailableException {
InputStream input = null;
try {
URL url = getServletContext().getResource(path);
// If the config isn't in the servlet context, try the class loader
// which allows the config files to be stored in a jar
if (url == null) {
url = getClass().getResource(path);
}
if (url == null) {
String msg = internal.getMessage("configMissing", path);
log.error(msg);
throw new UnavailableException(msg);
}
InputSource is = new InputSource(url.toExternalForm());
input = url.openStream();
is.setByteStream(input);
digester.parse(is);
} catch (MalformedURLException e) {
handleConfigException(path, e);
} catch (IOException e) {
handleConfigException(path, e);
} catch (SAXException e) {
handleConfigException(path, e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
throw new UnavailableException(e.getMessage());
}
}
}
} | 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 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-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 |
callback: (request: PublishRequest, response: PublishResponse) => void; | 0 | Java | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
public void testSetOrdersPseudoHeadersCorrectly() {
final HttpHeadersBase headers = newHttp2Headers();
final HttpHeadersBase other = newEmptyHeaders();
other.add("name2", "value2");
other.add("name3", "value3");
other.add("name4", "value4");
other.authority("foo");
final int headersSizeBefore = headers.size();
headers.set(other);
verifyPseudoHeadersFirst(headers);
verifyAllPseudoHeadersPresent(headers);
assertThat(headers.size()).isEqualTo(headersSizeBefore + 1);
assertThat(headers.authority()).isEqualTo("foo");
assertThat(headers.get("name2")).isEqualTo("value2");
assertThat(headers.get("name3")).isEqualTo("value3");
assertThat(headers.get("name4")).isEqualTo("value4");
} | 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 User getUser() {
return userId == null
? User.getUnknown()
: User.getById(userId, true)
;
} | 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 boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) {
return isAllowed;
} | 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 |
protected void configureReader(XMLReader reader, DefaultHandler handler)
throws DocumentException {
// configure lexical handling
SAXHelper.setParserProperty(reader, SAX_LEXICALHANDLER, handler);
// try alternate property just in case
SAXHelper.setParserProperty(reader, SAX_LEXICAL_HANDLER, handler);
// register the DeclHandler
if (includeInternalDTDDeclarations || includeExternalDTDDeclarations) {
SAXHelper.setParserProperty(reader, SAX_DECL_HANDLER, handler);
}
// string interning
SAXHelper.setParserFeature(reader, SAX_STRING_INTERNING,
isStringInternEnabled());
try {
// configure validation support
reader.setFeature("http://xml.org/sax/features/validation",
isValidating());
if (errorHandler != null) {
reader.setErrorHandler(errorHandler);
} else {
reader.setErrorHandler(handler);
}
} catch (Exception e) {
if (isValidating()) {
throw new DocumentException("Validation not supported for"
+ " XMLReader: " + reader, 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 PBEWithAESCBC()
{
super(new CBCBlockCipher(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 onSubmit()
{
final String sessionCsrfToken = getCsrfSessionToken();
final String postedCsrfToken = this.csrfTokenField.getInput();
if (StringUtils.equals(sessionCsrfToken, postedCsrfToken) == false) {
log.error("Cross site request forgery alert. csrf token doesn't match! session csrf token="
+ sessionCsrfToken
+ ", posted csrf token="
+ postedCsrfToken);
throw new InternalErrorException("errorpage.csrfError");
}
} | 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 |
void consecutiveSlashes() {
final PathAndQuery res = PathAndQuery.parse(
"/path//with///consecutive////slashes?/query//with///consecutive////slashes");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/path/with/consecutive/slashes");
assertThat(res.query()).isEqualTo("/query//with///consecutive////slashes");
// Encoded slashes
final PathAndQuery res2 = PathAndQuery.parse(
"/path%2F/with/%2F/consecutive//%2F%2Fslashes?/query%2F/with/%2F/consecutive//%2F%2Fslashes");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/path%2F/with/%2F/consecutive/%2F%2Fslashes");
assertThat(res2.query()).isEqualTo("/query%2F/with/%2F/consecutive//%2F%2Fslashes");
} | 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 |
void testHeaderNameNormalization() {
final HttpHeadersBase headers = newHttp2Headers();
headers.add("Foo", "bar");
assertThat(headers.getAll("foo")).containsExactly("bar");
assertThat(headers.getAll("fOO")).containsExactly("bar");
assertThat(headers.names()).contains(HttpHeaderNames.of("foo"))
.doesNotContain(AsciiString.of("Foo"));
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
protected static RootSearcher searchRootDirectory(Path fPath)
throws IOException {
RootSearcher rootSearcher = new RootSearcher();
Files.walkFileTree(fPath, rootSearcher);
return rootSearcher;
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
protected final String constructValidationUrl(final String ticket, final String serviceUrl) {
final Map<String, String> urlParameters = new HashMap<String, String>();
logger.debug("Placing URL parameters in map.");
urlParameters.put("ticket", ticket);
urlParameters.put("service", encodeUrl(serviceUrl));
if (this.renew) {
urlParameters.put("renew", "true");
}
logger.debug("Calling template URL attribute map.");
populateUrlAttributeMap(urlParameters);
logger.debug("Loading custom parameters from configuration.");
if (this.customParameters != null) {
urlParameters.putAll(this.customParameters);
}
final String suffix = getUrlSuffix();
final StringBuilder buffer = new StringBuilder(urlParameters.size() * 10 + this.casServerUrlPrefix.length()
+ suffix.length() + 1);
int i = 0;
buffer.append(this.casServerUrlPrefix);
if (!this.casServerUrlPrefix.endsWith("/")) {
buffer.append("/");
}
buffer.append(suffix);
for (Map.Entry<String, String> entry : urlParameters.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
if (value != null) {
buffer.append(i++ == 0 ? "?" : "&");
buffer.append(key);
buffer.append("=");
buffer.append(value);
}
}
return buffer.toString();
} | 0 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
private static String encodeQueryToPercents(@Nullable Bytes value) {
if (value == null) {
return null;
}
if (!value.hasEncodedBytes()) {
// Deprecated, but it fits perfect for our use case.
// noinspection deprecation
return new String(value.data, 0, 0, value.length);
}
// Slow path: some percent-encoded chars.
return slowEncodeQueryToPercents(value);
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
public void testMultiply1()
{
int COUNT = 1000;
for (int i = 0; i < COUNT; ++i)
{
ECFieldElement x = generateMultiplyInput_Random();
ECFieldElement y = generateMultiplyInput_Random();
BigInteger X = x.toBigInteger(), Y = y.toBigInteger();
BigInteger R = X.multiply(Y).mod(Q);
ECFieldElement z = x.multiply(y);
BigInteger Z = z.toBigInteger();
assertEquals(R, Z);
}
} | 1 | Java | CWE-19 | Data Processing Errors | Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information. | https://cwe.mitre.org/data/definitions/19.html | safe |
default boolean contains(String name) {
return get(name, Object.class).isPresent();
} | 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 |
static void setAttribute(TransformerFactory transformerFactory, String attributeName) {
try {
transformerFactory.setAttribute(attributeName, "");
} catch (IllegalArgumentException iae) {
if (Boolean.getBoolean(SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES)) {
LOGGER.warning("Enabling XXE protection failed. The attribute " + attributeName
+ " is not supported by the TransformerFactory. 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 attribute " + attributeName
+ " is not supported by the TransformerFactory. 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!!!", iae);
throw iae;
}
}
} | 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 headersContentLengthNegativeSign() throws Exception {
headersContentLengthSign("-1");
} | 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 createElementGT() {
DocumentHelper.createElement("element>name");
} | 1 | Java | CWE-91 | XML Injection (aka Blind XPath Injection) | The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system. | https://cwe.mitre.org/data/definitions/91.html | safe |
public void shouldNotGetModificationsFromOtherBranches() throws Exception {
makeACommitToSecondBranch();
hg(workingDirectory, "pull").runOrBomb(null);
List<Modification> actual = hgCommand.modificationsSince(new StringRevision(REVISION_0));
assertThat(actual.size(), is(2));
assertThat(actual.get(0).getRevision(), is(REVISION_2));
assertThat(actual.get(1).getRevision(), is(REVISION_1));
} | 0 | Java | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
public void testPseudoHeadersMustComeFirstWhenIterating() {
final HttpHeadersBase headers = newHttp2Headers();
verifyPseudoHeadersFirst(headers);
verifyAllPseudoHeadersPresent(headers);
} | 0 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
public OHttpSession removeSession(final String iSessionId) {
acquireExclusiveLock();
try {
return sessions.remove(iSessionId);
} finally {
releaseExclusiveLock();
}
}
| 0 | Java | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
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 |
private void testDESAndDESede(BigInteger g, BigInteger p)
throws Exception
{
DHParameterSpec dhParams = new DHParameterSpec(p, g, 256);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "BC");
keyGen.initialize(dhParams);
KeyPair kp = keyGen.generateKeyPair();
KeyAgreement keyAgreement = KeyAgreement.getInstance("DH", "BC");
keyAgreement.init(kp.getPrivate());
keyAgreement.doPhase(kp.getPublic(), true);
SecretKey key = keyAgreement.generateSecret("DES");
if (key.getEncoded().length != 8)
{
fail("DES length wrong");
}
if (!DESKeySpec.isParityAdjusted(key.getEncoded(), 0))
{
fail("DES parity wrong");
}
key = keyAgreement.generateSecret("DESEDE");
if (key.getEncoded().length != 24)
{
fail("DESEDE length wrong");
}
if (!DESedeKeySpec.isParityAdjusted(key.getEncoded(), 0))
{
fail("DESEDE parity wrong");
}
key = keyAgreement.generateSecret("Blowfish");
if (key.getEncoded().length != 16)
{
fail("Blowfish length wrong");
}
} | 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 testRandom(
int size)
throws Exception
{
AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DH", "BC");
a.init(size, new SecureRandom());
AlgorithmParameters params = a.generateParameters();
byte[] encodeParams = params.getEncoded();
AlgorithmParameters a2 = AlgorithmParameters.getInstance("DH", "BC");
a2.init(encodeParams);
// a and a2 should be equivalent!
byte[] encodeParams_2 = a2.getEncoded();
if (!areEqual(encodeParams, encodeParams_2))
{
fail("encode/decode parameters failed");
}
DHParameterSpec dhP = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class);
testGP("DH", size, 0, dhP.getG(), dhP.getP());
} | 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 Response attachToPost(Long messageKey, String filename, InputStream file, HttpServletRequest request) {
//load message
Message mess = fom.loadMessage(messageKey);
if(mess == null) {
return Response.serverError().status(Status.NOT_FOUND).build();
}
if(!forum.equalsByPersistableKey(mess.getForum())) {
return Response.serverError().status(Status.CONFLICT).build();
}
return attachToPost(mess, filename, file, request);
} | 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(ServerExplosionPacket packet, GeyserSession session) {
for (ExplodedBlockRecord record : packet.getExploded()) {
Vector3f pos = Vector3f.from(packet.getX() + record.getX(), packet.getY() + record.getY(), packet.getZ() + record.getZ());
ChunkUtils.updateBlock(session, BlockStateValues.JAVA_AIR_ID, pos.toInt());
}
Vector3f pos = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
// Since bedrock does not play an explosion sound and particles sound, we have to manually do so
LevelEventPacket levelEventPacket = new LevelEventPacket();
levelEventPacket.setType(packet.getRadius() >= 2.0f ? LevelEventType.PARTICLE_HUGE_EXPLODE : LevelEventType.PARTICLE_EXPLOSION);
levelEventPacket.setData(0);
levelEventPacket.setPosition(pos.toFloat());
session.sendUpstreamPacket(levelEventPacket);
LevelSoundEventPacket levelSoundEventPacket = new LevelSoundEventPacket();
levelSoundEventPacket.setRelativeVolumeDisabled(false);
levelSoundEventPacket.setBabySound(false);
levelSoundEventPacket.setExtraData(-1);
levelSoundEventPacket.setSound(SoundEvent.EXPLODE);
levelSoundEventPacket.setIdentifier(":");
levelSoundEventPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ()));
session.sendUpstreamPacket(levelSoundEventPacket);
if (packet.getPushX() > 0f || packet.getPushY() > 0f || packet.getPushZ() > 0f) {
SetEntityMotionPacket motionPacket = new SetEntityMotionPacket();
motionPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());
motionPacket.setMotion(Vector3f.from(packet.getPushX(), packet.getPushY(), packet.getPushZ()));
session.sendUpstreamPacket(motionPacket);
}
} | 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 checkConnection(UrlArgument repoUrl) {
final String ref = fullUpstreamRef();
final CommandLine commandLine = git().withArgs("ls-remote").withArg(repoUrl).withArg(ref);
final ConsoleResult result = commandLine.runOrBomb(new NamedProcessTag(repoUrl.forDisplay()));
if (!hasExactlyOneMatchingBranch(result)) {
throw new CommandLineException(format("The ref %s could not be found.", ref));
}
} | 0 | Java | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
public void setIncludeExternalDTDDeclarations(boolean include) {
this.includeExternalDTDDeclarations = include;
} | 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 void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new DHTest());
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
private void headersContentLengthSign(String length) throws Exception {
int padding = 10;
when(connection.isServer()).thenReturn(true);
decode().onHeadersRead(ctx, STREAM_ID, new DefaultHttp2Headers()
.set(HttpHeaderNames.CONTENT_LENGTH, length), padding, false);
// Verify that the event was absorbed and not propagated to the observer.
verify(listener, never()).onHeadersRead(eq(ctx), anyInt(),
any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean());
} | 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 multipleValuesPerNameIteratorEmpty() {
final HttpHeadersBase headers = newEmptyHeaders();
assertThat(headers.valueIterator("name")).isExhausted();
assertThatThrownBy(() -> headers.valueIterator("name").next())
.isInstanceOf(NoSuchElementException.class);
} | 0 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
protected StyleSignatureBasic getStyleSignature() {
return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.binary);
} | 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 static void testTruncated(TBase struct, TProtocol iprot) throws Exception {
try {
struct.read(iprot);
assertTrue("Not reachable", false);
} catch (TProtocolException ex) {
assertEquals(
"Not enough bytes to read the entire message, the data appears to be truncated",
ex.getMessage());
}
} | 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 int size() {
return ByteUtils.bitLength(k.decode());
} | 0 | Java | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | vulnerable |
public void notExistingDocumentFromUIButNameTooLong() 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(10);
context.setDoc(document);
when(mockRequest.getParameter("spaceReference")).thenReturn("Main");
when(mockRequest.getParameter("name")).thenReturn("Foo123456789");
// 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 see the error.
assertEquals("create", result);
// Check that the exception is properly set in the context for the UI to display.
XWikiException exception = (XWikiException) this.oldcore.getScriptContext().getAttribute("createException");
assertNotNull(exception);
assertEquals(XWikiException.ERROR_XWIKI_APP_DOCUMENT_PATH_TOO_LONG, exception.getCode());
// 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 void testGetBytesAndSetBytesWithFileChannel() throws IOException {
File file = PlatformDependent.createTempFile("file-channel", ".tmp", null);
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel();
// channelPosition should never be changed
long channelPosition = channel.position();
byte[] bytes = {'a', 'b', 'c', 'd'};
int len = bytes.length;
ByteBuf buffer = newBuffer(len);
buffer.resetReaderIndex();
buffer.resetWriterIndex();
buffer.writeBytes(bytes);
int oldReaderIndex = buffer.readerIndex();
assertEquals(len, buffer.getBytes(oldReaderIndex, channel, 10, len));
assertEquals(oldReaderIndex, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(buffer2.setBytes(oldWriterIndex, channel, 10, len), len);
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(oldWriterIndex));
assertEquals('b', buffer2.getByte(oldWriterIndex + 1));
assertEquals('c', buffer2.getByte(oldWriterIndex + 2));
assertEquals('d', buffer2.getByte(oldWriterIndex + 3));
buffer.release();
buffer2.release();
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
file.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 void testMultiply_OpenSSLBug()
{
int COUNT = 100;
for (int i = 0; i < COUNT; ++i)
{
ECFieldElement x = generateMultiplyInputA_OpenSSLBug();
ECFieldElement y = generateMultiplyInputB_OpenSSLBug();
BigInteger X = x.toBigInteger(), Y = y.toBigInteger();
BigInteger R = X.multiply(Y).mod(Q);
ECFieldElement z = x.multiply(y);
BigInteger Z = z.toBigInteger();
assertEquals(R, Z);
}
} | 1 | Java | CWE-19 | Data Processing Errors | Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information. | https://cwe.mitre.org/data/definitions/19.html | safe |
private static void verifyPeerName(PGStream stream, Properties info, SSLSocket newConnection)
throws PSQLException {
HostnameVerifier hvn;
String sslhostnameverifier = PGProperty.SSL_HOSTNAME_VERIFIER.get(info);
if (sslhostnameverifier == null) {
hvn = PGjdbcHostnameVerifier.INSTANCE;
sslhostnameverifier = "PgjdbcHostnameVerifier";
} else {
try {
hvn = (HostnameVerifier) instantiate(sslhostnameverifier, info, false, null);
} catch (Exception e) {
throw new PSQLException(
GT.tr("The HostnameVerifier class provided {0} could not be instantiated.",
sslhostnameverifier),
PSQLState.CONNECTION_FAILURE, e);
}
}
if (hvn.verify(stream.getHostSpec().getHost(), newConnection.getSession())) {
return;
}
throw new PSQLException(
GT.tr("The hostname {0} could not be verified by hostnameverifier {1}.",
stream.getHostSpec().getHost(), sslhostnameverifier),
PSQLState.CONNECTION_FAILURE);
} | 0 | Java | CWE-665 | Improper Initialization | The software does not initialize or incorrectly initializes a resource, which might leave the resource in an unexpected state when it is accessed or used. | https://cwe.mitre.org/data/definitions/665.html | vulnerable |
private String buildRedirectAuthnRequest(AuthnRequestType authnRequest, String relayState, boolean sign,
PrivateKey key, Algorithm algorithm) throws SAMLException {
try {
byte[] xml = marshallToBytes(PROTOCOL_OBJECT_FACTORY.createAuthnRequest(authnRequest), AuthnRequestType.class);
String encodedResult = deflateAndEncode(xml);
String parameters = "SAMLRequest=" + URLEncoder.encode(encodedResult, "UTF-8");
if (relayState != null) {
parameters += "&RelayState=" + URLEncoder.encode(relayState, "UTF-8");
}
if (sign && key != null && algorithm != null) {
Signature signature;
parameters += "&SigAlg=" + URLEncoder.encode(algorithm.uri, "UTF-8");
signature = Signature.getInstance(algorithm.name);
signature.initSign(key);
signature.update(parameters.getBytes(StandardCharsets.UTF_8));
String signatureParameter = Base64.getEncoder().encodeToString(signature.sign());
parameters += "&Signature=" + URLEncoder.encode(signatureParameter, "UTF-8");
}
return parameters;
} catch (Exception e) {
// Not possible but freak out
throw new SAMLException(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 boolean isUnsafe() {
return 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 sendResponse(Throwable error) throws IOException {
BytesStreamOutput stream = new BytesStreamOutput();
if (ThrowableObjectOutputStream.canSerialize(error) == false) {
assert false : "Can not serialize exception: " + error; // make sure tests fail
error = new NotSerializableTransportException(error);
}
try {
stream.skip(NettyHeader.HEADER_SIZE);
RemoteTransportException tx = new RemoteTransportException(transport.nodeName(), transport.wrapAddress(channel.getLocalAddress()), action, error);
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
} catch (NotSerializableException e) {
stream.reset();
stream.skip(NettyHeader.HEADER_SIZE);
RemoteTransportException tx = new RemoteTransportException(transport.nodeName(), transport.wrapAddress(channel.getLocalAddress()), action, new NotSerializableTransportException(error));
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
}
byte status = 0;
status = TransportStatus.setResponse(status);
status = TransportStatus.setError(status);
BytesReference bytes = stream.bytes();
ChannelBuffer buffer = bytes.toChannelBuffer();
NettyHeader.writeHeader(buffer, requestId, status, version);
channel.write(buffer);
transportServiceAdapter.onResponseSent(requestId, action, error);
} | 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 newDocumentWebHomeTopLevelSpaceButTerminalFromURL() throws Exception
{
// new document = xwiki:X.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(true);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Pass the tocreate=terminal request parameter
when(mockRequest.getParameter("tocreate")).thenReturn("terminal");
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify that the create template is rendered, so the UI is displayed for the user to enter the missing values.
assertEquals("create", result);
// Note: We can not create the "X" terminal document, since it is already at the top level of the hierarchy and
// none was able to be deducted from the given information. The user needs to specify more info in order to
// continue.
// 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 int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (keySpec == null) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
try {
setup(ad);
} catch (InvalidKeyException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (InvalidAlgorithmParameterException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
ghash.update(ciphertext, ciphertextOffset, dataLen);
ghash.pad(ad != null ? ad.length : 0, dataLen);
ghash.finish(iv, 0, 16);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
try {
int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset);
cipher.doFinal(plaintext, plaintextOffset + result);
} catch (IllegalBlockSizeException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (BadPaddingException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
return dataLen;
} | 0 | Java | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
public void setIgnoreComments(boolean ignoreComments) {
this.ignoreComments = ignoreComments;
} | 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 ECB()
{
super(new BlockCipherProvider()
{
public BlockCipher get()
{
return new AESEngine();
}
});
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
public static void testMapCompact() throws Exception {
TMemoryInputTransport buf = new TMemoryInputTransport(kCompactMapEncoding);
TProtocol iprot = new TCompactProtocol(buf);
testTruncated(new MyMapStruct(), 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 testGetBytesAndSetBytesWithFileChannel() 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.getBytes(oldReaderIndex, channel, 10, len));
assertEquals(oldReaderIndex, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(buffer2.setBytes(oldWriterIndex, channel, 10, len), len);
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(oldWriterIndex));
assertEquals('b', buffer2.getByte(oldWriterIndex + 1));
assertEquals('c', buffer2.getByte(oldWriterIndex + 2));
assertEquals('d', buffer2.getByte(oldWriterIndex + 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 |
private static File newFile() throws IOException {
File file = File.createTempFile("netty-", ".tmp");
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
return file;
} | 0 | Java | CWE-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 void test() throws Exception {
WebClient webClient = new WebClient();
webClient.setThrowExceptionOnFailingStatusCode(false);
for (int i = 0; i < 100; i++) {
// first, send out a hundred of poisoning requests
// each of these should leave a thread in a broken state
sendRequest(webClient, i, true);
}
for (int i = 0; i < 100; i++) {
// now send out normal requests to see if they are affected by the thread's broken state
String result = sendRequest(webClient, i, false);
Assert.assertFalse("Invalid state detected after " + (i + 1) + " requests", result.startsWith("bar"));
}
} | 1 | Java | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. | https://cwe.mitre.org/data/definitions/362.html | safe |
public void testInvalidMimeType() throws IOException, URISyntaxException {
checkMimeType("text/html", "text/plain");
} | 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 AuthnRequestParseResult parseRequest(byte[] xmlBytes) throws SAMLException {
String xml = new String(xmlBytes, StandardCharsets.UTF_8);
if (logger.isDebugEnabled()) {
logger.debug("SAMLRequest XML is\n{}", xml);
}
AuthnRequestParseResult result = new AuthnRequestParseResult();
result.document = parseFromBytes(xmlBytes);
result.authnRequest = unmarshallFromDocument(result.document, AuthnRequestType.class);
result.request = new AuthenticationRequest();
result.request.xml = xml;
result.request.id = result.authnRequest.getID();
result.request.issuer = result.authnRequest.getIssuer().getValue();
result.request.issueInstant = result.authnRequest.getIssueInstant().toGregorianCalendar().toZonedDateTime();
NameIDPolicyType nameIdPolicyType = result.authnRequest.getNameIDPolicy();
if (nameIdPolicyType == null) {
result.request.nameIdFormat = NameIDFormat.EmailAddress;
} else {
result.request.nameIdFormat = NameIDFormat.fromSAMLFormat(nameIdPolicyType.getFormat());
}
result.request.version = result.authnRequest.getVersion();
return result;
} | 0 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | vulnerable |
private static String sanitize(String mimeType) {
for (String accepted : new String[]{
"application/json",
"text/plain"
}) {
if (accepted.equalsIgnoreCase(mimeType)) {
return accepted;
}
}
return "text/plain";
} | 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 boolean isIgnoreComments() {
return ignoreComments;
} | 1 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | safe |
public void testInvalidGroupIds() {
testInvalidGroupId("John<b>Doe</b>",true);
testInvalidGroupId("Jane'Doe'",true);
testInvalidGroupId("John&Doe",true);
testInvalidGroupId("Jane\"\"Doe",true);
} | 1 | Java | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
public PlayerRobustConcise(TimingStyle type, String full, ISkinParam skinParam, TimingRuler ruler,
boolean compact) {
super(full, skinParam, ruler, compact);
this.type = type;
this.suggestedHeight = 0;
} | 0 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
public void setUp()
{
// Add BouncyCastle for testing.
Security.insertProviderAt(new BouncyCastleProvider(), 1);
System.out.println("WARNING: Using BouncyCastleProvider");
} | 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 static File getBaseDir() {
return new File(Jenkins.getInstance().getRootDir(),RekeySecretAdminMonitor.class.getName());
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public Cipher decrypt() {
try {
Cipher cipher = Secret.getCipher(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getKey());
return cipher;
} catch (GeneralSecurityException e) {
throw new AssertionError(e);
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public DefaultConfidentialStore() throws IOException, InterruptedException {
this(new File(Jenkins.getInstance().getRootDir(),"secrets"));
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void testCopy() throws Exception {
HttpHeadersBase headers = newEmptyHeaders();
headers.addLong("long", Long.MAX_VALUE);
headers.addInt("int", Integer.MIN_VALUE);
headers.addDouble("double", Double.MAX_VALUE);
headers.addFloat("float", Float.MAX_VALUE);
final long millis = System.currentTimeMillis();
headers.addTimeMillis("millis", millis);
headers.addObject("object", "Hello World");
headers.add("name", "value");
final HttpHeadersBase oldHeaders = headers;
headers = newEmptyHeaders();
headers.add(oldHeaders);
assertThat(headers.containsLong("long", Long.MAX_VALUE)).isTrue();
assertThat(headers.containsLong("long", Long.MIN_VALUE)).isFalse();
assertThat(headers.containsInt("int", Integer.MIN_VALUE)).isTrue();
assertThat(headers.containsInt("int", Integer.MAX_VALUE)).isFalse();
assertThat(headers.containsDouble("double", Double.MAX_VALUE)).isTrue();
assertThat(headers.containsDouble("double", Double.MIN_VALUE)).isFalse();
assertThat(headers.containsFloat("float", Float.MAX_VALUE)).isTrue();
assertThat(headers.containsFloat("float", Float.MIN_VALUE)).isFalse();
assertThat(headers.containsTimeMillis("millis", millis)).isTrue();
// This test doesn't work on midnight, January 1, 1970 UTC
assertThat(headers.containsTimeMillis("millis", 0)).isFalse();
assertThat(headers.containsObject("object", "Hello World")).isTrue();
assertThat(headers.containsObject("object", "")).isFalse();
assertThat(headers.contains("name", "value")).isTrue();
assertThat(headers.contains("name", "value1")).isFalse();
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public RoutingResultBuilder rawParam(String name, String value) {
pathParams().put(requireNonNull(name, "name"),
ArmeriaHttpUtil.decodePathParam(requireNonNull(value, "value")));
return this;
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
public static SecretKey decryptCEK(final PrivateKey priv,
final byte[] encryptedCEK,
final int keyLength,
final Provider provider)
throws JOSEException {
try {
Cipher cipher = CipherHelper.getInstance("RSA/ECB/PKCS1Padding", provider);
cipher.init(Cipher.DECRYPT_MODE, priv);
byte[] secretKeyBytes = cipher.doFinal(encryptedCEK);
if (ByteUtils.bitLength(secretKeyBytes) != keyLength) {
// CEK key length mismatch
return null;
}
return new SecretKeySpec(secretKeyBytes, "AES");
} catch (Exception e) {
// java.security.NoSuchAlgorithmException
// java.security.InvalidKeyException
// javax.crypto.IllegalBlockSizeException
// javax.crypto.BadPaddingException
throw new JOSEException("Couldn't decrypt Content Encryption Key (CEK): " + e.getMessage(), e);
}
} | 0 | Java | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | vulnerable |
protected void handleResponse(HttpRequest<?> request, MutableHttpResponse<?> response) {
HttpHeaders headers = request.getHeaders();
Optional<String> originHeader = headers.getOrigin();
originHeader.ifPresent(requestOrigin -> {
Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);
if (optionalConfig.isPresent()) {
CorsOriginConfiguration config = optionalConfig.get();
if (CorsUtil.isPreflightRequest(request)) {
Optional<HttpMethod> result = headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class);
setAllowMethods(result.get(), response);
Optional<List> allowedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, Argument.of(List.class, String.class));
allowedHeaders.ifPresent(val ->
setAllowHeaders(val, response)
);
setMaxAge(config.getMaxAge(), response);
}
setOrigin(requestOrigin, response);
setVary(response);
setExposeHeaders(config.getExposedHeaders(), response);
setAllowCredentials(config, response);
}
});
} | 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 void existingDocumentFromUITemplateProviderExistingButNoneSelected() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Submit from the UI spaceReference=X&name=Y
when(mockRequest.getParameter("spaceReference")).thenReturn("X");
when(mockRequest.getParameter("name")).thenReturn("Y");
// Mock 1 existing template provider
mockExistingTemplateProviders("XWiki.MyTemplateProvider",
new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST);
// 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 void translate(ServerStopSoundPacket packet, GeyserSession session) {
// Runs if all sounds are stopped
if (packet.getSound() == null) {
StopSoundPacket stopPacket = new StopSoundPacket();
stopPacket.setStoppingAllSound(true);
stopPacket.setSoundName("");
session.sendUpstreamPacket(stopPacket);
return;
}
String packetSound;
if (packet.getSound() instanceof BuiltinSound) {
packetSound = ((BuiltinSound) packet.getSound()).getName();
} else if (packet.getSound() instanceof CustomSound) {
packetSound = ((CustomSound) packet.getSound()).getName();
} else {
session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString());
return;
}
SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", ""));
session.getConnector().getLogger()
.debug("[StopSound] Sound mapping " + packetSound + " -> "
+ soundMapping + (soundMapping == null ? "[not found]" : "")
+ " - " + packet.toString());
String playsound;
if (soundMapping == null || soundMapping.getPlaysound() == null) {
// no mapping
session.getConnector().getLogger()
.debug("[StopSound] Defaulting to sound server gave us.");
playsound = packetSound;
} else {
playsound = soundMapping.getPlaysound();
}
StopSoundPacket stopSoundPacket = new StopSoundPacket();
stopSoundPacket.setSoundName(playsound);
// packet not mapped in the library
stopSoundPacket.setStoppingAllSound(false);
session.sendUpstreamPacket(stopSoundPacket);
session.getConnector().getLogger().debug("[StopSound] Packet sent - " + packet.toString() + " --> " + stopSoundPacket);
} | 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 soapBindingIsNotPossibleForClientsWithSamlEcpFlowAttributeFalse() {
// Disable ECP_FLOW_ENABLED switch
getCleanup().addCleanup(ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_ECP_SP)
.setAttribute(SamlConfigAttributes.SAML_ALLOW_ECP_FLOW, "false")
.setAttribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "false")
.setAttribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false")
.update());
new SamlClientBuilder()
.authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_ECP_SP, SAML_ASSERTION_CONSUMER_URL_ECP_SP, SOAP)
.basicAuthentication(bburkeUser)
.build()
.execute(response -> {
assertThat(response, statusCodeIsHC(Response.Status.INTERNAL_SERVER_ERROR));
try {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage(null, response.getEntity().getContent());
String faultDetail = soapMessage.getSOAPBody().getFault().getDetail().getValue();
assertThat(faultDetail, is(equalTo("Client is not allowed to use ECP profile.")));
} catch (SOAPException | IOException e) {
throw new RuntimeException(e);
}
});
} | 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 |
private File tempFile() throws IOException {
String newpostfix;
String diskFilename = getDiskFilename();
if (diskFilename != null) {
newpostfix = '_' + diskFilename;
} else {
newpostfix = getPostfix();
}
File tmpFile;
if (getBaseDirectory() == null) {
// create a temporary file
tmpFile = File.createTempFile(getPrefix(), newpostfix);
} else {
tmpFile = File.createTempFile(getPrefix(), newpostfix, new File(
getBaseDirectory()));
}
if (deleteOnExit()) {
// See https://github.com/netty/netty/issues/10351
DeleteFileOnExitHook.add(tmpFile.getPath());
}
return tmpFile;
} | 0 | Java | CWE-379 | Creation of Temporary File in Directory with Insecure Permissions | The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file. | https://cwe.mitre.org/data/definitions/379.html | vulnerable |
public RoundedContainer(Dimension2D dim, double titleHeight, double attributeHeight, HColor borderColor,
HColor backColor, HColor imgBackcolor, UStroke stroke, double rounded, double shadowing) {
if (dim.getWidth() == 0) {
throw new IllegalArgumentException();
}
this.rounded = rounded;
this.dim = dim;
this.imgBackcolor = imgBackcolor;
this.titleHeight = titleHeight;
this.borderColor = borderColor;
this.backColor = backColor;
this.attributeHeight = attributeHeight;
this.stroke = stroke;
this.shadowing = shadowing;
} | 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 IESCipher(IESEngine engine, int ivLength)
{
this.engine = engine;
this.ivLength = ivLength;
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
public static AsciiString of(CharSequence name) {
if (name instanceof AsciiString) {
return of((AsciiString) name);
}
final String lowerCased = Ascii.toLowerCase(requireNonNull(name, "name"));
final AsciiString cached = map.get(lowerCased);
if (cached != null) {
return cached;
}
return validate(AsciiString.cached(lowerCased));
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
void testToString() {
HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name1", "value2");
headers.add("name2", "value3");
assertThat(headers.toString()).isEqualTo("[name1=value1, name1=value2, name2=value3]");
headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name2", "value2");
headers.add("name3", "value3");
assertThat(headers.toString()).isEqualTo("[name1=value1, name2=value2, name3=value3]");
headers = newEmptyHeaders();
headers.add("name1", "value1");
assertThat(headers.toString()).isEqualTo("[name1=value1]");
headers = newEmptyHeaders();
headers.endOfStream(true);
headers.add("name1", "value1");
assertThat(headers.toString()).isEqualTo("[EOS, name1=value1]");
headers = newEmptyHeaders();
assertThat(headers.toString()).isEqualTo("[]");
headers = newEmptyHeaders();
headers.endOfStream(true);
assertThat(headers.toString()).isEqualTo("[EOS]");
} | 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 Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator translator) {
VFSContainer currentContainer = folderComponent.getCurrentContainer();
VFSContainer rootContainer = folderComponent.getRootContainer();
if (!VFSManager.exists(currentContainer)) {
status = FolderCommandStatus.STATUS_FAILED;
showError(translator.translate("FileDoesNotExist"));
return null;
}
status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
if (status == FolderCommandStatus.STATUS_FAILED) {
return null;
}
FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
if (status == FolderCommandStatus.STATUS_FAILED) {
return null;
}
boolean selectionWithContainer = false;
List<String> filenames = selection.getFiles();
List<VFSLeaf> leafs = new ArrayList<>();
for (String file : filenames) {
VFSItem item = currentContainer.resolve(file);
if (item instanceof VFSContainer) {
selectionWithContainer = true;
} else if (item instanceof VFSLeaf) {
leafs.add((VFSLeaf) item);
}
}
if (selectionWithContainer) {
if (leafs.isEmpty()) {
wControl.setError(getTranslator().translate("send.mail.noFileSelected"));
return null;
} else {
setFormWarning(getTranslator().translate("send.mail.selectionContainsFolder"));
}
}
setFiles(rootContainer, leafs);
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 HMACConfidentialKey(Class owner, String shortName) {
this(owner,shortName,Integer.MAX_VALUE);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
protected void run() throws IOException, InterruptedException {
final String secret = in.readUTF();
final String nodeName = in.readUTF();
if(!SLAVE_SECRET.mac(nodeName).equals(secret)) {
error(out, "Unauthorized access");
return;
}
SlaveComputer computer = (SlaveComputer) Jenkins.getInstance().getComputer(nodeName);
if(computer==null) {
error(out, "No such slave: "+nodeName);
return;
}
if(computer.getChannel()!=null) {
error(out, nodeName+" is already connected to this master. Rejecting this connection.");
return;
}
out.println(Engine.GREETING_SUCCESS);
jnlpConnect(computer);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public URL createURL(String spaces, String name, String queryString, String anchor, String wikiId,
XWikiContext context, FilesystemExportContext exportContext) throws Exception
{
// Check if the current user has the right to view the SX file. We do this since this is what would happen
// in XE when a SX action is called (check done in XWikiAction).
// Note that we cannot just open an HTTP connection to the SX action here since we wouldn't be authenticated...
// Thus we have to simulate the same behavior as the SX action...
List<String> spaceNames = this.legacySpaceResolve.resolve(spaces);
DocumentReference sxDocumentReference = new DocumentReference(wikiId, spaceNames, name);
this.authorizationManager.checkAccess(Right.VIEW, sxDocumentReference);
// Set the SX document as the current document in the XWiki Context since unfortunately the SxSource code
// uses the current document in the context instead of accepting it as a parameter...
XWikiDocument sxDocument = context.getWiki().getDocument(sxDocumentReference, context);
Map<String, Object> backup = new HashMap<>();
XWikiDocument.backupContext(backup, context);
try {
sxDocument.setAsContextDoc(context);
return processSx(spaceNames, name, queryString, context, exportContext);
} finally {
XWikiDocument.restoreContext(backup, context);
}
} | 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 DropFileContainer(final String id, final String mimeType) {
super(id);
this.mimeType = mimeType;
main = new WebMarkupContainer("main");
add(main);
} | 0 | Java | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | vulnerable |
private void ondata(String data) {
try {
this.decoder.add(data);
} catch (DecodingException e) {
this.onerror(e);
}
} | 0 | Java | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
private void headersContentLength(boolean negative) throws Exception {
int padding = 10;
when(connection.isServer()).thenReturn(true);
decode().onHeadersRead(ctx, STREAM_ID, new DefaultHttp2Headers()
.setLong(HttpHeaderNames.CONTENT_LENGTH, negative ? -1L : 1L), padding, true);
// Verify that the event was absorbed and not propagated to the observer.
verify(listener, never()).onHeadersRead(eq(ctx), anyInt(),
any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean());
} | 1 | Java | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
protected String quoteOneItem(String inputString, boolean isExecutable)
{
char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() );
return StringUtils.quoteAndEscape(
inputString,
isExecutable ? getExecutableQuoteDelimiter() : getArgumentQuoteDelimiter(),
escapeChars,
getQuotingTriggerChars(),
'\\',
unconditionallyQuote
);
} | 1 | Java | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
public PBEWithSHA1AESCBC128()
{
super(new CBCBlockCipher(new AESFastEngine()), PKCS12, SHA1, 128, 16);
} | 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 XMLFilter getXMLFilter() {
return xmlFilter;
} | 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 iteratorSetShouldFail() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1", "value2", "value3");
headers.add("name2", "value4");
assertThat(headers.size()).isEqualTo(4);
assertThatThrownBy(() -> headers.iterator().next().setValue(""))
.isInstanceOf(UnsupportedOperationException.class);
} | 0 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
private void checkCorsGetOrigin(final String in, final String out) throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(in);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
}
},
new Runnable() {
public void run() {
response.setHeader("Access-Control-Allow-Origin", out);
response.setHeader("Access-Control-Allow-Credentials","true");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(200);
}
}
);
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
servlet.destroy();
} | 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 accessAllowed() {
expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true);
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 doFilter(ServletRequest srequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
/* HttpServletRequest request = (HttpServletRequest) srequest;
//final String realIp = request.getHeader(X_FORWARDED_FOR);
//if (realIp != null) {
filterChain.doFilter(new XssHttpServletRequestWrapper(request) {
*//**
public String getRemoteAddr() {
return realIp;
}
public String getRemoteHost() {
return realIp;
}
**//*
}, response);
return;
//}
*/
} | 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 BadBlockException(String msg, Throwable cause)
{
super(msg);
this.cause = cause;
} | 1 | Java | CWE-361 | 7PK - Time and State | This category represents one of the phyla in the Seven Pernicious Kingdoms vulnerability classification. It includes weaknesses related to the improper management of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. According to the authors of the Seven Pernicious Kingdoms, "Distributed computation is about time and state. That is, in order for more than one component to communicate, state must be shared, and all that takes time. Most programmers anthropomorphize their work. They think about one thread of control carrying out the entire program in the same way they would if they had to do the job themselves. Modern computers, however, switch between tasks very quickly, and in multi-core, multi-CPU, or distributed systems, two events may take place at exactly the same time. Defects rush to fill the gap between the programmer's model of how a program executes and what happens in reality. These defects are related to unexpected interactions between threads, processes, time, and information. These interactions happen through shared state: semaphores, variables, the file system, and, basically, anything that can store information." | https://cwe.mitre.org/data/definitions/361.html | safe |
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 void writeResponse( HttpServletResponse response,
String ok ) throws IOException {
response.setContentType( "text/html" );
response.getWriter().write( ok );
} | 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 AnnotatedLargeText getLogText() {
return new AnnotatedLargeText<RekeySecretAdminMonitor>(getLogFile(), Charset.defaultCharset(),
!isRewriterActive(),this);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public boolean isMetadataFileValid(OLATResource videoResource) {
VFSContainer baseContainer = FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);
VFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);
try {
VideoMetadata meta = (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);
return meta != null;
} catch (Exception e) {
return false;
}
} | 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 static void validateHeader(CharSequence name, Iterable<? extends CharSequence> values) {
validateHeader(name);
values.forEach(HttpUtils::validateHeader);
} | 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 HMACConfidentialKey(String id) {
this(id,Integer.MAX_VALUE);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void shouldGetLatestModifications() throws Exception {
List<Modification> actual = hgCommand.latestOneModificationAsModifications();
assertThat(actual.size(), is(1));
final Modification modification = actual.get(0);
assertThat(modification.getComment(), is("test"));
assertThat(modification.getUserName(), is("cruise"));
assertThat(modification.getModifiedFiles().size(), is(1));
} | 0 | Java | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.