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 OldECIES()
{
super(new OldIESEngine(new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest())));
} | 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 Throwable getCause()
{
return 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 |
public UploadFileResponse getCloudUrl(String contextPath, String uri, String finalFilePath, HttpServletRequest request) {
UploadFileResponse uploadFileResponse = new UploadFileResponse();
// try push to cloud
Map<String, String[]> map = new HashMap<>();
map.put("fileInfo", new String[]{finalFilePath + "," + uri});
map.put("name", new String[]{"uploadService"});
String url;
try {
List<Map> urls = HttpUtil.getInstance().sendGetRequest(Constants.pluginServer + "/service", map
, new HttpJsonArrayHandle<Map>(), PluginHelper.genHeaderMapByRequest(request)).getT();
if (urls != null && !urls.isEmpty()) {
url = (String) urls.get(0).get("url");
if (!url.startsWith("https://") && !url.startsWith("http://")) {
String tUrl = url;
if (!url.startsWith("/")) {
tUrl = "/" + url;
}
url = contextPath + tUrl;
}
} else {
url = contextPath + uri;
}
} catch (Exception e) {
url = contextPath + uri;
LOGGER.error(e);
}
uploadFileResponse.setUrl(url);
return uploadFileResponse;
} | 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 |
public String getId() {
return id;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public static void main(String[] args) throws LifecycleException {
String webappDirLocation;
if (Constants.IN_JAR) {
webappDirLocation = "webapp";
} else {
webappDirLocation = "src/main/webapp/";
}
Tomcat tomcat = new Tomcat();
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
tomcat.setPort(Integer.valueOf(webPort));
tomcat.getConnector();
// Declare an alternative location for your "WEB-INF/classes" dir
// Servlet 3.0 annotation will work
File additionWebInfClasses;
if (Constants.IN_JAR) {
additionWebInfClasses = new File("");
} else {
additionWebInfClasses = new File("target/classes");
}
tomcat.setBaseDir(additionWebInfClasses.toString());
//idea的路径eclipse启动的路径有区别
if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) {
webappDirLocation = "web/" + webappDirLocation;
}
tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
} | 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 |
final protected SymbolContext getContext() {
if (UseStyle.useBetaStyle() == false)
return getContextLegacy();
final Style style = getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder());
final HColor lineColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(),
skinParam.getIHtmlColorSet());
final HColor backgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(),
skinParam.getIHtmlColorSet());
return new SymbolContext(backgroundColor, lineColor).withStroke(getStroke());
} | 0 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
private ECFieldElement generateMultiplyInput_Random()
{
return fe(new BigInteger(DP.getCurve().getFieldSize() + 32, RANDOM).mod(Q));
} | 1 | Java | CWE-19 | Data Processing Errors | Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information. | https://cwe.mitre.org/data/definitions/19.html | safe |
public void 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 void failingExample() {
assertThat(ConstraintViolations.format(validator.validate(new FailingExample())))
.containsExactlyInAnyOrder(FAILED_RESULT);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
} | 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 setPaths(final String s) {
try {
final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes("8859_1")));
this.paths = (WorkBundle) ois.readObject();
} catch (Exception e) {
logger.error("Cannot deserialize WorkBundle using {} bytes", s.length(), e);
throw new IllegalArgumentException("Cannot deserialize WorkBundle");
}
} | 0 | Java | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
public static void main(String[] args) {
// Will serve all static file are under "/public" in classpath if the route isn't consumed by others routes.
staticFiles.location("/public");
get("/hello", (request, response) -> {
return "Hello World!";
});
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
void testPseudoHeadersWithClearDoesNotLeak() {
final HttpHeadersBase headers = newHttp2Headers();
assertThat(headers.isEmpty()).isFalse();
headers.clear();
assertThat(headers.isEmpty()).isTrue();
// Combine 2 headers together, make sure pseudo headers stay up front.
headers.add("name1", "value1");
headers.scheme("nothing");
verifyPseudoHeadersFirst(headers);
final HttpHeadersBase other = newEmptyHeaders();
other.add("name2", "value2");
other.authority("foo");
verifyPseudoHeadersFirst(other);
headers.add(other);
verifyPseudoHeadersFirst(headers);
// Make sure the headers are what we expect them to be, and no leaking behind the scenes.
assertThat(headers.size()).isEqualTo(4);
assertThat(headers.get("name1")).isEqualTo("value1");
assertThat(headers.get("name2")).isEqualTo("value2");
assertThat(headers.scheme()).isEqualTo("nothing");
assertThat(headers.authority()).isEqualTo("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 |
public void testSerializeAndParsePublicJWKSet()
throws Exception {
ECKey ecKey = new ECKey.Builder(ECKey.Curve.P_256,
new Base64URL("abc"),
new Base64URL("def"))
.keyUse(KeyUse.ENCRYPTION)
.algorithm(JWEAlgorithm.ECDH_ES)
.keyID("1234")
.build();
RSAKey rsaKey = new RSAKey.Builder(new Base64URL("abc"), new Base64URL("def"))
.keyUse(KeyUse.SIGNATURE)
.algorithm(JWSAlgorithm.RS256)
.keyID("5678")
.build();
JWKSet keySet = new JWKSet();
keySet.getKeys().add(ecKey);
keySet.getKeys().add(rsaKey);
assertEquals(0, keySet.getAdditionalMembers().size());
keySet.getAdditionalMembers().put("setID", "xyz123");
assertEquals(1, keySet.getAdditionalMembers().size());
String s = keySet.toString();
keySet = JWKSet.parse(s);
assertNotNull(keySet);
assertEquals(2, keySet.getKeys().size());
// Check first EC key
ecKey = (ECKey)keySet.getKeys().get(0);
assertNotNull(ecKey);
assertEquals(ECKey.Curve.P_256, ecKey.getCurve());
assertEquals("abc", ecKey.getX().toString());
assertEquals("def", ecKey.getY().toString());
assertEquals(KeyUse.ENCRYPTION, ecKey.getKeyUse());
assertNull(ecKey.getKeyOperations());
assertEquals(JWEAlgorithm.ECDH_ES, ecKey.getAlgorithm());
assertEquals("1234", ecKey.getKeyID());
// Check second RSA key
rsaKey = (RSAKey)keySet.getKeys().get(1);
assertNotNull(rsaKey);
assertEquals("abc", rsaKey.getModulus().toString());
assertEquals("def", rsaKey.getPublicExponent().toString());
assertEquals(KeyUse.SIGNATURE, rsaKey.getKeyUse());
assertNull(rsaKey.getKeyOperations());
assertEquals(JWSAlgorithm.RS256, rsaKey.getAlgorithm());
assertEquals("5678", rsaKey.getKeyID());
// Check additional JWKSet members
assertEquals(1, keySet.getAdditionalMembers().size());
assertEquals("xyz123", (String)keySet.getAdditionalMembers().get("setID"));
} | 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 |
private JsonNode yamlStreamToJson(InputStream yamlStream) {
Yaml reader = new Yaml();
ObjectMapper mapper = new ObjectMapper();
return mapper.valueToTree(reader.load(yamlStream));
} | 0 | Java | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
protected final void loadMoreGuaranteed() throws IOException {
if (!loadMore()) { _reportInvalidEOF(); }
} | 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 Stream(final InputStream inner) {
this.inner = inner;
} | 1 | 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 | safe |
public void encodeByteArrayDeepInJson() throws JSONException {
JSONObject data = new JSONObject("{a: \"hi\", b: {}, c: {a: \"bye\", b: {}}}");
data.getJSONObject("b").put("why", new byte[3]);
data.getJSONObject("c").getJSONObject("b").put("a", new byte[6]);
Packet<JSONObject> packet = new Packet<>(Parser.BINARY_EVENT);
packet.data = data;
packet.id = 999;
packet.nsp = "/deep";
Helpers.testBin(packet);
} | 0 | Java | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
public void setIncludeInternalDTDDeclarations(boolean include) {
this.includeInternalDTDDeclarations = 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 long writeHtmlTo(long start, Writer w) throws IOException {
ConsoleAnnotationOutputStream caw = new ConsoleAnnotationOutputStream(
w, createAnnotator(Stapler.getCurrentRequest()), context, charset);
long r = super.writeLogTo(start,caw);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Cipher sym = Secret.getCipher("AES");
sym.init(Cipher.ENCRYPT_MODE, Jenkins.getInstance().getSecretKeyAsAES128());
ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(new CipherOutputStream(baos,sym)));
oos.writeLong(System.currentTimeMillis()); // send timestamp to prevent a replay attack
oos.writeObject(caw.getConsoleAnnotator());
oos.close();
StaplerResponse rsp = Stapler.getCurrentResponse();
if (rsp!=null)
rsp.setHeader("X-ConsoleAnnotator", new String(Base64.encode(baos.toByteArray())));
} catch (GeneralSecurityException e) {
throw new IOException2(e);
}
return r;
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public static byte[] computeLength(final byte[] aad) {
final int bitLength = ByteUtils.bitLength(aad);
return ByteBuffer.allocate(8).putLong(bitLength).array();
} | 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 boolean isOriginAllowed(String pOrigin,boolean pStrictChecking) {
return restrictor.isOriginAllowed(pOrigin, pStrictChecking);
} | 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 IESwithAES()
{
super(new IESEngine(new DHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
new PaddedBufferedBlockCipher(new AESEngine())));
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
public ProductServletConfigurator(ServerConfig serverConfig, ShiroFilter shiroFilter, GitFilter gitFilter,
GitPreReceiveCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet,
WicketServlet wicketServlet, WebSocketManager webSocketManager,
AttachmentUploadServlet attachmentUploadServlet, ServletContainer jerseyServlet) {
this.serverConfig = serverConfig;
this.shiroFilter = shiroFilter;
this.gitFilter = gitFilter;
this.preReceiveServlet = preReceiveServlet;
this.postReceiveServlet = postReceiveServlet;
this.wicketServlet = wicketServlet;
this.webSocketManager = webSocketManager;
this.jerseyServlet = jerseyServlet;
this.attachmentUploadServlet = attachmentUploadServlet;
} | 0 | Java | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
public static C3P0Config extractXmlConfigFromInputStream(InputStream is) throws Exception
{
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
fact.setExpandEntityReferences(false);
DocumentBuilder db = fact.newDocumentBuilder();
Document doc = db.parse( is );
return extractConfigFromXmlDoc(doc);
} | 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 |
/*package*/ static SecretKey getLegacyKey() throws UnsupportedEncodingException, GeneralSecurityException {
String secret = SECRET;
if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128();
return Util.toAes128Key(secret);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static boolean pathContainsDoubleDots(Bytes path) {
final int length = path.length;
byte b0 = 0;
byte b1 = 0;
byte b2 = '/';
for (int i = 1; i < length; i++) {
final byte b3 = path.data[i];
// Flag if the last four bytes are `/../`.
if (b1 == '.' && b2 == '.' && isSlash(b0) && isSlash(b3)) {
return true;
}
b0 = b1;
b1 = b2;
b2 = b3;
}
// Flag if the last three bytes are `/..`.
return b1 == '.' && b2 == '.' && isSlash(b0);
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
public int read() throws IOException {
return inner.read();
} | 1 | Java | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | safe |
private String getSkinResourcePath(String resource)
{
String skinFolder = getSkinFolder();
String resourcePath = skinFolder + resource;
// Prevent inclusion of templates from other directories
Path normalizedResource = Paths.get(resourcePath).normalize();
// Protect against directory attacks.
if (!normalizedResource.startsWith(skinFolder)) {
LOGGER.warn("Direct access to skin file [{}] refused. Possible break-in attempt!", normalizedResource);
return null;
}
return resourcePath;
} | 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 ModelAndView recover(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String usernameOrEmail = StringUtils.trimToNull(request.getParameter("usernameOrEmail"));
if (usernameOrEmail != null) {
map.put("usernameOrEmail", usernameOrEmail);
User user = getUserByUsernameOrEmail(usernameOrEmail);
boolean captchaOk;
if (settingsService.isCaptchaEnabled()) {
String recaptchaResponse = request.getParameter("g-recaptcha-response");
ReCaptcha captcha = new ReCaptcha(settingsService.getRecaptchaSecretKey());
captchaOk = recaptchaResponse != null && captcha.isValid(recaptchaResponse);
} else {
captchaOk = true;
}
if (!captchaOk) {
map.put("error", "recover.error.invalidcaptcha");
} else if (user == null) {
map.put("error", "recover.error.usernotfound");
} else if (user.getEmail() == null) {
map.put("error", "recover.error.noemail");
} else {
String password = RandomStringUtils.randomAlphanumeric(8);
if (emailPassword(password, user.getUsername(), user.getEmail())) {
map.put("sentTo", user.getEmail());
user.setLdapAuthenticated(false);
user.setPassword(password);
securityService.updateUser(user);
} else {
map.put("error", "recover.error.sendfailed");
}
}
}
if (settingsService.isCaptchaEnabled()) {
map.put("recaptchaSiteKey", settingsService.getRecaptchaSiteKey());
}
return new ModelAndView("recover", "model", map);
} | 0 | Java | CWE-335 | Incorrect Usage of Seeds in Pseudo-Random Number Generator (PRNG) | The software uses a Pseudo-Random Number Generator (PRNG) but does not correctly manage seeds. | https://cwe.mitre.org/data/definitions/335.html | vulnerable |
public void testCurveCheckOk()
throws Exception {
ECPublicKey ephemeralPublicKey = generateECPublicKey(ECKey.Curve.P_256);
ECPrivateKey privateKey = generateECPrivateKey(ECKey.Curve.P_256);
ECDH.ensurePointOnCurve(ephemeralPublicKey, privateKey);
} | 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 int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (!haskey) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
setup(ad);
ghash.update(ciphertext, ciphertextOffset, dataLen);
ghash.pad(ad != null ? ad.length : 0, dataLen);
ghash.finish(enciv, 0, 16);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);
return dataLen;
} | 0 | Java | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
public void translate(ServerEntityRemoveEffectPacket packet, GeyserSession session) {
Entity entity;
if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
entity = session.getPlayerEntity();
session.getEffectCache().removeEffect(packet.getEffect());
} else {
entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
}
if (entity == null)
return;
MobEffectPacket mobEffectPacket = new MobEffectPacket();
mobEffectPacket.setEvent(MobEffectPacket.Event.REMOVE);
mobEffectPacket.setRuntimeEntityId(entity.getGeyserId());
mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect()));
session.sendUpstreamPacket(mobEffectPacket);
} | 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 |
error_t nicSendPacket(NetInterface *interface, const NetBuffer *buffer,
size_t offset, NetTxAncillary *ancillary)
{
error_t error;
bool_t status;
//Gather entropy
netContext.entropy += netGetSystemTickCount();
#if (TRACE_LEVEL >= TRACE_LEVEL_DEBUG)
//Retrieve the length of the packet
size_t length = netBufferGetLength(buffer) - offset;
//Debug message
TRACE_DEBUG("Sending packet (%" PRIuSIZE " bytes)...\r\n", length);
TRACE_DEBUG_NET_BUFFER(" ", buffer, offset, length);
#endif
//Check whether the interface is enabled for operation
if(interface->configured && interface->nicDriver != NULL)
{
//Loopback interface?
if(interface->nicDriver->type == NIC_TYPE_LOOPBACK)
{
//The loopback interface is always available
status = TRUE;
}
else
{
//Wait for the transmitter to be ready to send
status = osWaitForEvent(&interface->nicTxEvent, NIC_MAX_BLOCKING_TIME);
}
//Check whether the specified event is in signaled state
if(status)
{
//Disable interrupts
interface->nicDriver->disableIrq(interface);
//Send the packet
error = interface->nicDriver->sendPacket(interface, buffer, offset,
ancillary);
//Re-enable interrupts if necessary
if(interface->configured)
{
interface->nicDriver->enableIrq(interface);
}
}
else
{
//If the transmitter is busy, then drop the packet
error = NO_ERROR;
}
}
else
{
//Report an error
error = ERROR_INVALID_INTERFACE;
}
//Return status code
return error;
} | 0 | Java | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes()
{
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/local/'something else'" );
sh.setExecutable( "chmod" );
String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );
assertEquals( "/bin/sh -c cd '/usr/local/'\"'\"'something else'\"'\"'' && 'chmod'", executable );
} | 1 | Java | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
public void initWithAgentDiscoveryAndUrlCreationAfterGet() throws ServletException, IOException {
checkMulticastAvailable();
prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true");
try {
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
String url = "http://10.9.11.1:9876/jolokia";
StringBuffer buf = new StringBuffer();
buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getRequestURL()).andReturn(buf);
expect(request.getRequestURI()).andReturn(buf.toString());
expect(request.getContextPath()).andReturn("/jolokia");
expect(request.getAuthType()).andReturn("BASIC");
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
JolokiaDiscovery discovery = new JolokiaDiscovery("test",LogHandler.QUIET);
List<JSONObject> in = discovery.lookupAgents();
assertTrue(in.size() > 0);
for (JSONObject json : in) {
if (json.get("url") != null && json.get("url").equals(url)) {
assertTrue((Boolean) json.get("secured"));
return;
}
}
fail("Failed, because no message had an URL");
} finally {
servlet.destroy();
}
} | 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 ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException {
int type = read();
if (type < 0) {
throw new EOFException();
}
switch (type) {
case ThrowableObjectOutputStream.TYPE_EXCEPTION:
return ObjectStreamClass.lookup(Exception.class);
case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:
return ObjectStreamClass.lookup(StackTraceElement.class);
case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:
return super.readClassDescriptor();
case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:
String className = readUTF();
Class<?> clazz = loadClass(className);
return ObjectStreamClass.lookup(clazz);
default:
throw new StreamCorruptedException(
"Unexpected class descriptor type: " + type);
}
} | 0 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
public void addViolation(String msg) {
violationOccurred = true;
context.buildConstraintViolationWithTemplate(msg)
.addConstraintViolation();
} | 0 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
void allReservedCharacters() {
final PathAndQuery res = PathAndQuery.parse("/#/:[]@!$&'()*+,;=?a=/#/:[]@!$&'()*+,;=");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/#/:[]@!$&'()*+,;=");
assertThat(res.query()).isEqualTo("a=/#/:[]@!$&'()*+,;=");
final PathAndQuery res2 =
PathAndQuery.parse("/%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F" +
"?a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/#%2F:[]@!$&'()*+,;=?");
assertThat(res2.query()).isEqualTo("a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F");
} | 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 testInvalidGroupId(final String groupId, final boolean mustFail) {
adminPage();
findElementByLink("Configure Users, Groups and On-Call Roles").click();
findElementByLink("Configure Groups").click();
findElementByLink("Add new group").click();
enterText(By.id("groupName"), groupId);
enterText(By.id("groupComment"), "SmokeTestComment");
findElementByXpath("//button[@type='submit' and text()='OK']").click();
if (mustFail) {
try {
final Alert alert = wait.withTimeout(Duration.of(5, ChronoUnit.SECONDS)).until(ExpectedConditions.alertIsPresent());
alert.dismiss();
} catch (final Exception e) {
LOG.debug("Got an exception waiting for a 'invalid group ID' alert.", e);
throw e;
}
} else {
wait.until(ExpectedConditions.elementToBeClickable(By.name("finish")));
}
} | 1 | Java | CWE-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 |
/*package*/ static SecretKey getLegacyKey() throws UnsupportedEncodingException, GeneralSecurityException {
String secret = SECRET;
if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128();
return Util.toAes128Key(secret);
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public Object getTarget() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
return this;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void handle(final HttpServletRequest request, final HttpServletResponse response)
throws Exception
{
new ContextualHttpServletRequest(request)
{
@Override
public void process() throws Exception
{
ServletContexts.instance().setRequest(request);
if (request.getQueryString() == null)
{
throw new ServletException("Invalid request - no component specified");
}
Set<Component> components = new HashSet<Component>();
Set<Type> types = new HashSet<Type>();
response.setContentType("text/javascript");
Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
String componentName = ((String) e.nextElement()).trim();
Component component = Component.forName(componentName);
if (component == null)
{
log.error(String.format("Component not found: [%s]", componentName));
throw new ServletException("Invalid request - component not found.");
}
else
{
components.add(component);
}
}
generateComponentInterface(components, response.getOutputStream(), types);
}
}.run();
} | 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 |
private String getTitleQTI12(QuestionItemImpl item) {
try {
VFSLeaf leaf = qpoolService.getRootLeaf(item);
Item xmlItem = QTIEditHelper.readItemXml(leaf);
return xmlItem.getTitle();
} catch (NullPointerException e) {
log.warn("Cannot read files from dir: " + item.getDirectory());
}
return null;
} | 0 | Java | CWE-91 | XML Injection (aka Blind XPath Injection) | The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system. | https://cwe.mitre.org/data/definitions/91.html | vulnerable |
public void preflightCheckNegative() {
String origin = "http://bla.com";
String headers ="X-Data: Test";
expect(backend.isOriginAllowed(origin,false)).andReturn(false);
replay(backend);
Map<String,String> ret = handler.handleCorsPreflightRequest(origin, headers);
assertNull(ret.get("Access-Control-Allow-Origin"));
} | 1 | Java | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
default List<MediaType> accept() {
return getAll(HttpHeaders.ACCEPT)
.stream()
.flatMap(x -> Arrays.stream(x.split(",")))
.flatMap(s -> ConversionService.SHARED.convert(s, MediaType.class).map(Stream::of).orElse(Stream.empty()))
.distinct()
.collect(Collectors.toList());
} | 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 |
@Test public void dotDotsOkayWhenNotFullPathSegment() {
class Example {
@GET("/foo{ping}bar/") //
Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) {
return null;
}
}
assertMalformedRequest(Example.class, "/./");
assertMalformedRequest(Example.class, "/../");
assertThat(buildRequest(Example.class, ".").url().encodedPath()).isEqualTo("/foo.bar/");
assertThat(buildRequest(Example.class, "..").url().encodedPath()).isEqualTo("/foo..bar/");
} | 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 void beforeClass() throws IOException {
final Random r = new Random();
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) r.nextInt(255);
}
tmp = PlatformDependent.createTempFile("netty-traffic", ".tmp", null);
tmp.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tmp);
out.write(BYTES);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
} | 1 | Java | CWE-378 | Creation of Temporary File With Insecure Permissions | Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack. | https://cwe.mitre.org/data/definitions/378.html | safe |
public PACLFreeMarkerTemplate(
String templateId, String templateContent, String errorTemplateId,
String errorTemplateContent, Map<String, Object> context,
Configuration configuration,
TemplateContextHelper templateContextHelper,
StringTemplateLoader stringTemplateLoader, PACLPolicy paclPolicy) {
super(
templateId, templateContent, errorTemplateId, errorTemplateContent,
context, configuration, templateContextHelper,
stringTemplateLoader);
_paclPolicy = paclPolicy;
} | 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 String getAndSet(String newValue) {
String old = value;
value = newValue;
return old;
} | 1 | Java | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. | https://cwe.mitre.org/data/definitions/362.html | safe |
public static ResourceEvaluation evaluate(File file, String filename) {
ResourceEvaluation eval = new ResourceEvaluation();
try {
ImsManifestFileFilter visitor = new ImsManifestFileFilter();
Path fPath = PathUtils.visit(file, filename, visitor);
if(visitor.hasManifest()) {
Path realManifestPath = visitor.getManifestPath();
Path manifestPath = fPath.resolve(realManifestPath);
RootSearcher rootSearcher = new RootSearcher();
Files.walkFileTree(fPath, rootSearcher);
if(rootSearcher.foundRoot()) {
manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);
} else {
manifestPath = fPath.resolve(IMS_MANIFEST);
}
Document doc = IMSLoader.loadIMSDocument(manifestPath);
if(validateImsManifest(doc)) {
if(visitor.hasEditorTreeModel()) {
XMLScanner scanner = new XMLScanner();
scanner.scan(visitor.getEditorTreeModelPath());
eval.setValid(!scanner.hasEditorTreeModelMarkup());
} else {
eval.setValid(true);
}
} else {
eval.setValid(false);
}
} else {
eval.setValid(false);
}
PathUtils.closeSubsequentFS(fPath);
} catch (IOException | IllegalArgumentException e) {
log.error("", e);
eval.setValid(false);
}
return eval;
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
public static void zipFolder(String srcFolder, String destZipFile, String ignore) throws Exception {
try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
ZipOutputStream zip = new ZipOutputStream(fileWriter)){
addFolderToZip("", srcFolder, zip, ignore);
zip.flush();
}
} | 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 Stream<? extends Arguments> provideArguments(ExtensionContext context) {
return Stream.of(H1C, H1, H2C, H2)
.map(protocol -> Arguments.of(WebClient.of(
clientFactory,
protocol.uriText() + "://127.0.0.1:" +
(protocol.isTls() ? server.httpsPort() : server.httpPort()))));
} | 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 BigInteger getRandomizer(BigInteger q, SecureRandom provided)
{
// Calculate a random multiple of q to add to k. Note that g^q = 1 (mod p), so adding multiple of q to k does not change r.
int randomBits = 7;
return new BigInteger(randomBits, provided != null ? provided : new SecureRandom()).add(BigInteger.valueOf(128)).multiply(q);
} | 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 |
public QName(String name, Namespace namespace) {
this.name = (name == null) ? "" : name;
this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE
: namespace;
if (this.namespace.equals(Namespace.NO_NAMESPACE)) {
validateName(this.name);
} else {
validateNCName(this.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 translate(ServerEntityMetadataPacket packet, GeyserSession session) {
Entity entity;
if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
entity = session.getPlayerEntity();
} else {
entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
}
if (entity == null) return;
for (EntityMetadata metadata : packet.getMetadata()) {
try {
entity.updateBedrockMetadata(metadata, session);
} catch (ClassCastException e) {
// Class cast exceptions are really the only ones we're going to get in normal gameplay
// Because some entity rewriters forget about some values
// Any other errors are actual bugs
session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.network.translator.metadata.failed", metadata, entity.getEntityType()));
session.getConnector().getLogger().debug("Entity Java ID: " + entity.getEntityId() + ", Geyser ID: " + entity.getGeyserId());
if (session.getConnector().getConfig().isDebugMode()) {
e.printStackTrace();
}
}
}
entity.updateBedrockMetadata(session);
// Update the interactive tag, if necessary
if (session.getMouseoverEntity() != null && session.getMouseoverEntity().getEntityId() == entity.getEntityId()) {
InteractiveTagManager.updateTag(session, entity);
}
} | 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 <T extends Serializable> T serialize(T t) throws IOException, ClassNotFoundException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try (ThrowableObjectOutputStream outputStream = new ThrowableObjectOutputStream(stream)) {
outputStream.writeObject(t);
}
try (ThrowableObjectInputStream in = new ThrowableObjectInputStream(new ByteArrayInputStream(stream.toByteArray()))) {
return (T) in.readObject();
}
} | 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 FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String filename = file.getFileName().toString();
Path normalizedPath = file.normalize();
if(!normalizedPath.startsWith(destDir)) {
throw new IOException("Invalid ZIP");
}
if(filename.endsWith(WikiManager.WIKI_PROPERTIES_SUFFIX)) {
String f = convertAlternativeFilename(file.toString());
final Path destFile = Paths.get(wikiDir.toString(), f);
resetAndCopyProperties(file, destFile);
} else if (filename.endsWith(WIKI_FILE_SUFFIX)) {
String f = convertAlternativeFilename(file.toString());
final Path destFile = Paths.get(wikiDir.toString(), f);
Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
} else if (!filename.contains(WIKI_FILE_SUFFIX + "-")
&& !filename.contains(WIKI_PROPERTIES_SUFFIX + "-")) {
final Path destFile = Paths.get(mediaDir.toString(), file.toString());
Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
}
return FileVisitResult.CONTINUE;
} | 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 List<String> getRawCommandLine( String executable, String[] arguments )
{
List<String> commandLine = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
if ( executable != null )
{
String preamble = getExecutionPreamble();
if ( preamble != null )
{
sb.append( preamble );
}
if ( isQuotedExecutableEnabled() )
{
char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() );
sb.append( StringUtils.quoteAndEscape( getExecutable(), getExecutableQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\', false ) );
}
else
{
sb.append( getExecutable() );
}
}
for ( int i = 0; i < arguments.length; i++ )
{
if ( sb.length() > 0 )
{
sb.append( " " );
}
if ( isQuotedArgumentsEnabled() )
{
char[] escapeChars = getEscapeChars( isSingleQuotedArgumentEscaped(), isDoubleQuotedArgumentEscaped() );
sb.append( StringUtils.quoteAndEscape( arguments[i], getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), getArgumentEscapePattern(), false ) );
}
else
{
sb.append( arguments[i] );
}
}
commandLine.add( sb.toString() );
return commandLine;
} | 0 | Java | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
protected BigDecimal bcdToBigDecimal() {
if (usingBytes) {
// Converting to a string here is faster than doing BigInteger/BigDecimal arithmetic.
BigDecimal result = new BigDecimal(toNumberString());
if (isNegative()) {
result = result.negate();
}
return result;
} else {
long tempLong = 0L;
for (int shift = (precision - 1); shift >= 0; shift--) {
tempLong = tempLong * 10 + getDigitPos(shift);
}
BigDecimal result = BigDecimal.valueOf(tempLong);
result = result.scaleByPowerOfTen(scale);
if (isNegative())
result = result.negate();
return result;
}
} | 0 | Java | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
public void testSelectByType() {
JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyType(KeyType.RSA).build());
List<JWK> keyList = new ArrayList<>();
keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").build());
keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build());
JWKSet jwkSet = new JWKSet(keyList);
List<JWK> matches = selector.select(jwkSet);
RSAKey key1 = (RSAKey)matches.get(0);
assertEquals(KeyType.RSA, key1.getKeyType());
assertEquals("1", key1.getKeyID());
assertEquals(1, matches.size());
} | 0 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | vulnerable |
public void doHandle(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(getHostName(address),
address.getAddress().getHostAddress(),
extractOriginOrReferer(pExchange));
String method = pExchange.getRequestMethod();
// If a callback is given, check this is a valid javascript function name
validateCallbackIfGiven(parsedUri);
// 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-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 close(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
target.appendJavaScript("$('#" + getMainContainerMarkupId() + "').modal('hide');");
} | 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 debug() throws IOException, ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.DEBUG.getKeyValue(), "true"},null,"No access restrictor found",null);
context.log(find("URI:"));
context.log(find("Path-Info:"));
context.log(find("Request:"));
context.log(find("time:"));
context.log(find("Response:"));
context.log(find("TestDetector"),isA(RuntimeException.class));
expectLastCall().anyTimes();
replay(config, context);
servlet.init(config);
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
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 boolean isValid(Object value, ConstraintValidatorContext context) {
final ViolationCollector collector = new ViolationCollector(context);
context.disableDefaultConstraintViolation();
for (ValidationCaller caller : methodMap.computeIfAbsent(value.getClass(), this::findMethods)) {
caller.setValidationObject(value);
caller.call(collector);
}
return !collector.hasViolationOccurred();
} | 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 SshPublicKeyCredential(String userName, String passphrase, File keyFile) throws SVNException {
this.userName = userName;
this.passphrase = Scrambler.scramble(passphrase);
Random r = new Random();
StringBuilder buf = new StringBuilder();
for(int i=0;i<16;i++)
buf.append(Integer.toHexString(r.nextInt(16)));
this.id = buf.toString();
try {
File savedKeyFile = getKeyFile();
FileUtils.copyFile(keyFile,savedKeyFile);
setFilePermissions(savedKeyFile, "600");
} catch (IOException e) {
throw new SVNException(
SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to save private key").initCause(e));
}
} | 0 | Java | CWE-255 | Credentials Management Errors | Weaknesses in this category are related to the management of credentials. | https://cwe.mitre.org/data/definitions/255.html | vulnerable |
public void testHeaderNameEndsWithControlChar1f() {
testHeaderNameEndsWithControlChar(0x1f);
} | 1 | Java | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (request.getParameter("path") != null) {
writeFile(ioService.get(new URI(request.getParameter("path"))), getFileItem(request));
writeResponse(response, "OK");
} else if (request.getParameter("folder") != null) {
writeFile(
ioService.get(new URI(request.getParameter("folder") + "/" + request.getParameter("fileName"))),
getFileItem(request));
writeResponse(response, "OK");
}
} catch (FileUploadException e) {
logError(e);
writeResponse(response, "FAIL");
} catch (URISyntaxException e) {
logError(e);
writeResponse(response, "FAIL");
}
} | 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 boolean isValidating() {
return validating;
} | 1 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | safe |
private void sendResponse(HttpServletResponse pResp, HttpServletRequest pReq, JSONAware pJson) throws IOException {
String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());
setContentType(pResp,
MimeTypeUtil.getResponseMimeType(
pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue()),
configMimeType, callback
));
pResp.setStatus(HttpServletResponse.SC_OK);
setNoCacheHeaders(pResp);
if (pJson == null) {
pResp.setContentLength(-1);
} else {
if (isStreamingEnabled(pReq)) {
sendStreamingResponse(pResp, callback, (JSONStreamAware) pJson);
} else {
// Fallback, send as one object
// TODO: Remove for 2.0 where should support only streaming
sendAllJSON(pResp, callback, pJson);
}
}
} | 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 Runnable getDiscoveryRequestSetup(final String url) {
return new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andStubReturn(null);
expect(request.getHeader("Referer")).andStubReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null);
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
StringBuffer buf = new StringBuffer();
buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getRequestURL()).andReturn(buf);
expect(request.getRequestURI()).andReturn("/jolokia" + HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getContextPath()).andReturn("/jolokia");
expect(request.getAuthType()).andReturn("BASIC");
expect(request.getAttribute("subject")).andReturn(null);
expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null);
}
};
} | 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 Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>();
set.add(TestResource.class);
return set;
} | 1 | Java | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
void malformedHeaderValue(WebClient client) throws Exception {
final String payloadRaw = "my-header\r\nnot-a-header: should_be_illegal";
final String payload = URLEncoder.encode(payloadRaw, StandardCharsets.US_ASCII.name());
final String path = "/headers-custom?param=" + payload;
final AggregatedHttpResponse res = client.get(path).aggregate().get();
assertThat(res.status()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(res.headers().get("not-a-header")).isNull();
} | 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 translate(ServerBlockChangePacket packet, GeyserSession session) {
Position pos = packet.getRecord().getPosition();
boolean updatePlacement = session.getConnector().getPlatformType() != PlatformType.SPIGOT && // Spigot simply listens for the block place event
session.getConnector().getWorldManager().getBlockAt(session, pos) != packet.getRecord().getBlock();
ChunkUtils.updateBlock(session, packet.getRecord().getBlock(), pos);
if (updatePlacement) {
this.checkPlace(session, packet);
}
this.checkInteract(session, packet);
} | 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 Map<String, Object> getHelperUtilities() {
Map<String, Object> helperUtilities = super.getHelperUtilities();
// Enum util
helperUtilities.put(
"enumUtil", BeansWrapper.getDefaultInstance().getEnumModels());
// Object util
helperUtilities.put("objectUtil", new LiferayObjectConstructor());
// Portlet preferences
helperUtilities.put(
"freeMarkerPortletPreferences", new TemplatePortletPreferences());
// Static class util
helperUtilities.put(
"staticUtil", BeansWrapper.getDefaultInstance().getStaticModels());
return helperUtilities;
} | 1 | Java | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
public void testWhitespaceBeforeTransferEncoding02() {
String requestStr = "POST / HTTP/1.1" +
" Transfer-Encoding : chunked\r\n" +
"Host: target.com" +
"Content-Length: 65\r\n\r\n" +
"0\r\n\r\n" +
"GET /maliciousRequest HTTP/1.1\r\n" +
"Host: evilServer.com\r\n" +
"Foo: x";
testInvalidHeaders0(requestStr);
} | 0 | Java | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | vulnerable |
protected DispatchHandler getDispatchHandler() {
if (dispatchHandler == null) {
dispatchHandler = new DispatchHandler();
}
return dispatchHandler;
} | 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 RechnungCostEditTablePanel(final String id)
{
super(id);
feedbackPanel = new FeedbackPanel("feedback");
ajaxComponents.register(feedbackPanel);
add(feedbackPanel);
this.form = new Form<AbstractRechnungsPositionDO>("form");
add(form);
rows = new RepeatingView("rows");
form.add(rows);
} | 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 shouldNotAllowToListFileOutsideRoot() throws Exception {
// given
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(containsString("this String argument must not contain the substring [..]"));
// when
logViewEndpoint.view("../somefile", null, null, null);
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
public static void testSetBinary() throws Exception {
TMemoryInputTransport buf = new TMemoryInputTransport(kBinarySetEncoding);
TProtocol iprot = new TBinaryProtocol(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 getLogFile(@PathVariable("filename") String fileName, HttpServletResponse response) throws Exception {
InputStream inputStream = null;
try {
//Validate/Sanitize user input filename using a standard library, prevent from path traversal
String logFileName = getFilePath() + File.separator + FilenameUtils.getName(fileName);
File fileToDownload = new File(logFileName);
inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
logger.debug("Request could not be completed at this moment. Please try again.");
logger.debug(e.getStackTrace().toString());
throw e;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
logger.debug(e.getStackTrace().toString());
throw e;
}
}
}
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
public void destroy() {
StringResourceLoader.clearRepositories();
_classLoaderVelocityContexts.clear();
_classLoaderVelocityContexts = null;
_restrictedVelocityContext = null;
_standardVelocityContext = null;
_velocityEngine = 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 |
public void existingDocumentTerminalFromUICheckEscaping() 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&name=Z&tocreate=termina
when(mockRequest.getParameter("spaceReference")).thenReturn("X.Y");
when(mockRequest.getParameter("name")).thenReturn("Z");
when(mockRequest.getParameter("tocreate")).thenReturn("terminal");
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note: We are creating X.Y.Z instead of X.Y.Z.WebHome because the tocreate parameter says "terminal".
verify(mockURLFactory).createURL("X.Y", "Z", "edit", "template=&parent=Main.WebHome&title=Z", null, "xwiki",
context);
} | 0 | Java | CWE-862 | Missing Authorization | The software does not perform an authorization check when an actor attempts to access a resource or perform an action. | https://cwe.mitre.org/data/definitions/862.html | vulnerable |
public void validateFail(ViolationCollector col) {
col.addViolation("{1+1}");
col.addViolation("{value}", Collections.singletonMap("value", "VALUE"));
col.addViolation("No parameter", Collections.singletonMap("value", "VALUE"));
col.addViolation("{value} {unsetParameter}", Collections.singletonMap("value", "VALUE"));
col.addViolation("{value", Collections.singletonMap("value", "VALUE"));
col.addViolation("value}", Collections.singletonMap("value", "VALUE"));
col.addViolation("{ value }", Collections.singletonMap("value", "VALUE"));
col.addViolation("Mixed ${'value'} {value}", Collections.singletonMap("value", "VALUE"));
col.addViolation("Nested {value}", Collections.singletonMap("value", "${'nested'}"));
col.addViolation("{property}", "{value}", Maps.of("property", "PROPERTY", "value", "VALUE"));
col.addViolation("{property}", 1, "{value}", Maps.of("property", "PROPERTY", "value", "VALUE"));
col.addViolation("{property}", "{key}", "{value}", Maps.of("property", "PROPERTY", "key", "KEY", "value", "VALUE"));
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public void addViolation(String propertyName, String message, Map<String, Object> messageParameters) {
violationOccurred = true;
getContextWithMessageParameters(messageParameters)
.buildConstraintViolationWithTemplate(sanitizeTemplate(message))
.addPropertyNode(propertyName)
.addConstraintViolation();
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public ErrorHandler getErrorHandler() {
return errorHandler;
} | 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 IdImpl(String id) {
this.id = id;
} | 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 testValidUserIds() {
testInvalidUserId("John-Doe",false);
testInvalidUserId("Jane/Doe",false);
testInvalidUserId("John.Doe",false);
testInvalidUserId("Jane#Doe", false);
testInvalidUserId("John@Döe.com", false);
testInvalidUserId("JohnDoé", false);
} | 1 | Java | CWE-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 Map<String, ServiceStat> getServiceStats(URI serviceUri) {
AuthorizationContext ctx = null;
if (this.isAuthorizationEnabled()) {
ctx = OperationContext.getAuthorizationContext();
this.setSystemAuthorizationContext();
}
ServiceStats stats = this.sender.sendStatsGetAndWait(serviceUri);
if (this.isAuthorizationEnabled()) {
this.setAuthorizationContext(ctx);
}
return stats.entries;
} | 1 | Java | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | safe |
public CryptoConfidentialKey(String id) {
super(id);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public RechnungCostEditTablePanel(final String id)
{
super(id);
feedbackPanel = new FeedbackPanel("feedback");
ajaxComponents.register(feedbackPanel);
add(feedbackPanel);
this.form = new Form<AbstractRechnungsPositionDO>("form") {
@Override
protected void onSubmit()
{
super.onSubmit();
csrfTokenHandler.onSubmit();
}
};
add(form);
csrfTokenHandler = new CsrfTokenHandler(form);
rows = new RepeatingView("rows");
form.add(rows);
} | 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 SAXReader(DocumentFactory factory) {
this.factory = factory;
} | 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 doNotShowUserDetailsInOfflineCause() throws Exception {
DumbSlave slave = j.createOnlineSlave();
final Computer computer = slave.toComputer();
computer.setTemporarilyOffline(true, new OfflineCause.UserCause(User.get("username"), "msg"));
verifyOfflineCause(computer);
} | 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 addViolation(String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addConstraintViolation();
} | 0 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
private static int findNonWhitespace(AppendableCharSequence sb, int offset, boolean validateOWS) {
for (int result = offset; result < sb.length(); ++result) {
char c = sb.charAtUnsafe(result);
if (!Character.isWhitespace(c)) {
return result;
} else if (validateOWS && !isOWS(c)) {
// Only OWS is supported for whitespace
throw new IllegalArgumentException("Invalid separator, only a single space or horizontal tab allowed," +
" but received a '" + c + "' (0x" + Integer.toHexString(c) + ")");
}
}
return sb.length();
} | 0 | Java | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | vulnerable |
private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {
JSONAware json = null;
try {
// Check access policy
requestHandler.checkAccess(allowDnsReverseLookup ? pReq.getRemoteHost() : null,
pReq.getRemoteAddr(),
getOriginOrReferer(pReq));
// If a callback is given, check this is a valid javascript function name
validateCallbackIfGiven(pReq);
// Remember the agent URL upon the first request. Needed for discovery
updateAgentDetailsIfNeeded(pReq);
// Dispatch for the proper HTTP request method
json = handleSecurely(pReqHandler, pReq, pResp);
} catch (Throwable exp) {
try {
json = requestHandler.handleThrowable(
exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
} catch (Throwable exp2) {
exp2.printStackTrace();
}
} finally {
setCorsHeader(pReq, pResp);
if (json == null) {
json = requestHandler.handleThrowable(new Exception("Internal error while handling an exception"));
}
sendResponse(pResp, pReq, json);
}
} | 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 JsonParser allowClass(final String classPattern) {
if (super.classnameWhitelist == null) {
super.classnameWhitelist = new ArrayList<>();
}
classnameWhitelist.add(classPattern);
return this;
} | 1 | 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 | safe |
public void getResourceIllegalTraversal() {
testingClient.server().run(session -> {
try {
Theme theme = session.theme().getTheme("base", Theme.Type.LOGIN);
Assert.assertNull(theme.getResourceAsStream("../templates/test.ftl"));
} catch (IOException e) {
Assert.fail(e.getMessage());
}
});
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void sharp() {
final PathAndQuery res = parse("/#?a=b#1");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/#");
assertThat(res.query()).isEqualTo("a=b#1");
// '%23' in a query string should never be decoded into '#'.
final PathAndQuery res2 = parse("/%23?a=b%231");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/#");
assertThat(res2.query()).isEqualTo("a=b%231");
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
void iterateEmptyHeadersShouldThrow() {
final Iterator<Map.Entry<AsciiString, String>> iterator = newEmptyHeaders().iterator();
assertThat(iterator.hasNext()).isFalse();
assertThatThrownBy(iterator::next).isInstanceOf(NoSuchElementException.class);
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
for (int i = 0; i < TO_PERCENT_ENCODED_CHARS.length; i++) {
TO_PERCENT_ENCODED_CHARS[i] = String.format("%%%02X", i).toCharArray();
} | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.