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 static String[] tokenizeToStringArray(String str, String delimiters) {
if (str == null) {
return null;
}
final StringTokenizer st = new StringTokenizer(str, delimiters);
final List<String> tokens = new ArrayList<String>();
while (st.hasMoreTokens()) {
final String token = st.nextToken().trim();
if (token.length() > 0) {
tokens.add(token);
}
}
return tokens.toArray(new String[tokens.size()]);
} | 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 Cipher decrypt() {
try {
Cipher cipher = Secret.getCipher(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getKey());
return cipher;
} catch (GeneralSecurityException e) {
throw new AssertionError(e);
}
} | 0 | Java | CWE-326 | Inadequate Encryption Strength | The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required. | https://cwe.mitre.org/data/definitions/326.html | vulnerable |
public void headersWithSameNamesButDifferentValuesShouldNotBeEquivalent() {
final HttpHeadersBase headers1 = newEmptyHeaders();
headers1.add("name1", "value1");
final HttpHeadersBase headers2 = newEmptyHeaders();
headers1.add("name1", "value2");
assertThat(headers1).isNotEqualTo(headers2);
} | 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 multipleValuesPerNameIterator() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name1", "value2");
assertThat(headers.size()).isEqualTo(2);
final List<String> values = ImmutableList.copyOf(headers.valueIterator("name1"));
assertThat(values).containsExactly("value1", "value2");
} | 0 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) {
PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcastPacket();
broadcastPacket.setTrackingId(packet.getTrackingId());
// Fetch the stored Loadstone
LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId());
// If we don't have data for that ID tell the client its not found
if (pos == null) {
broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND);
session.sendUpstreamPacket(broadcastPacket);
return;
}
broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE);
// Build the nbt data for the update
NbtMapBuilder builder = NbtMap.builder();
builder.putInt("dim", DimensionUtils.javaToBedrock(pos.getDimension()));
builder.putString("id", String.format("%08X", packet.getTrackingId()));
builder.putByte("version", (byte) 1); // Not sure what this is for
builder.putByte("status", (byte) 0); // Not sure what this is for
// Build the position for the update
IntList posList = new IntArrayList();
posList.add(pos.getX());
posList.add(pos.getY());
posList.add(pos.getZ());
builder.putList("pos", NbtType.INT, posList);
broadcastPacket.setTag(builder.build());
session.sendUpstreamPacket(broadcastPacket);
} | 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 testTikaDocs() throws Exception {
String[] expected = {"testEXCEL.xls", "13824",
"testHTML.html", "167",
"testOpenOffice2.odt", "26448",
"testPDF.pdf", "34824",
"testPPT.ppt", "16384",
"testRTF.rtf", "3410",
"testTXT.txt", "49",
"testWORD.doc", "19456",
"testXML.xml", "766"};
File f = new File(getClass().getResource("test-documents.rar").toURI());
Archive archive = null;
try {
archive = new Archive(f);
FileHeader fileHeader = archive.nextFileHeader();
int i = 0;
while (fileHeader != null) {
assertTrue(fileHeader.getFileNameString().contains(expected[i++]));
assertEquals(Long.parseLong(expected[i++]), fileHeader.getUnpSize());
fileHeader = archive.nextFileHeader();
}
} finally {
archive.close();
}
} | 1 | Java | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
public HMACConfidentialKey(Class owner, String shortName, int length) {
this(owner.getName()+'.'+shortName,length);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
String sequence = req.getParameter("sequence");
String poison = req.getParameter("poison");
if ("getAndSet".equals(action)) {
// the value should always be foo
String value = bean.getAndSet("bar" + sequence);
resp.getWriter().println(value);
if (poison != null) {
// this is a poisoning request
// normal applications should never do something like this
// we just do this to cause an exception to be thrown out of ConversationContext.deactivate
req.removeAttribute(ConversationNamingScheme.PARAMETER_NAME);
}
} else {
throw new IllegalArgumentException(action);
}
} | 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 |
protected Response attachToPost(Message mess, String filename, InputStream file, HttpServletRequest request) {
Identity identity = getIdentity(request);
if(identity == null) {
return Response.serverError().status(Status.UNAUTHORIZED).build();
} else if (!identity.equalsByPersistableKey(mess.getCreator())) {
if(mess.getModifier() == null || !identity.equalsByPersistableKey(mess.getModifier())) {
return Response.serverError().status(Status.UNAUTHORIZED).build();
}
}
VFSContainer container = fom.getMessageContainer(mess.getForum().getKey(), mess.getKey());
VFSItem item = container.resolve(filename);
VFSLeaf attachment = null;
if(item == null) {
attachment = container.createChildLeaf(filename);
} else {
filename = VFSManager.rename(container, filename);
if(filename == null) {
return Response.serverError().status(Status.NOT_ACCEPTABLE).build();
}
attachment = container.createChildLeaf(filename);
}
try(OutputStream out = attachment.getOutputStream(false)) {
IOUtils.copy(file, out);
} catch (IOException e) {
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
} finally {
FileUtils.closeSafely(file);
}
return Response.ok().build();
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
public void testMatchOperation() {
JWKMatcher matcher = new JWKMatcher.Builder().keyOperation(KeyOperation.DECRYPT).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.DECRYPT))).build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()));
assertEquals("key_ops=decrypt", matcher.toString());
} | 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 boolean check(String pOrigin, boolean pIsStrictCheck) {
// Method called during strict checking but we have not configured that
// So the check passes always.
if (pIsStrictCheck && !strictChecking) {
return true;
}
if (patterns == null || patterns.size() == 0) {
return true;
}
for (Pattern pattern : patterns) {
if (pattern.matcher(pOrigin).matches()) {
return true;
}
}
return false;
} | 1 | Java | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
public void validateConcreteScmMaterial(ValidationContext validationContext) {
if (getView() == null || getView().trim().isEmpty()) {
errors.add(VIEW, "P4 view cannot be empty.");
}
if (StringUtils.isBlank(getServerAndPort())) {
errors.add(SERVER_AND_PORT, "P4 port cannot be empty.");
}
validateEncryptedPassword();
} | 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 setUnconditionalQuoting(boolean unconditionallyQuote)
{
this.unconditionallyQuote = 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 |
void validSaveNewTranslation() throws Exception
{
when(mockForm.getLanguage()).thenReturn("fr");
when(mockClonedDocument.getTranslatedDocument("fr", this.context)).thenReturn(mockClonedDocument);
when(mockClonedDocument.getDocumentReference()).thenReturn(new DocumentReference("xwiki", "My", "Page"));
when(mockClonedDocument.getStore()).thenReturn(this.oldcore.getMockStore());
when(xWiki.getStore()).thenReturn(this.oldcore.getMockStore());
context.put("ajax", true);
when(xWiki.isMultiLingual(this.context)).thenReturn(true);
when(mockRequest.getParameter("previousVersion")).thenReturn("1.1");
when(mockRequest.getParameter("isNew")).thenReturn("true");
assertFalse(saveAction.save(this.context));
assertEquals(new Version("1.1"), this.context.get("SaveAction.savedObjectVersion"));
verify(this.xWiki).checkSavingDocument(eq(USER_REFERENCE), any(XWikiDocument.class), eq(""),
eq(false), eq(this.context));
verify(this.xWiki).saveDocument(any(XWikiDocument.class), eq(""), eq(false), eq(this.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 String render(TemplateEngineTypeEnum engineType, String templateContent, Map<String, Object> context) {
if (StrUtil.isEmpty(templateContent)) {
return StrUtil.EMPTY;
}
TemplateEngine templateEngine = templateEngineMap.get(engineType);
Assert.notNull(templateEngine, "未找到对应的模板引擎:{}", engineType);
return templateEngine.render(templateContent, context);
} | 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 translate(ServerEntityRotationPacket packet, GeyserSession session) {
Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
entity = session.getPlayerEntity();
}
if (entity == null) return;
entity.updateRotation(session, packet.getYaw(), packet.getPitch(), packet.isOnGround());
} | 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 ResponseEntity<Resource> download(@PathVariable String key) {
LitemallStorage litemallStorage = litemallStorageService.findByKey(key);
if (key == null) {
ResponseEntity.notFound();
}
String type = litemallStorage.getType();
MediaType mediaType = MediaType.parseMediaType(type);
Resource file = storageService.loadAsResource(key);
if (file == null) {
ResponseEntity.notFound();
}
return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + file.getFilename() + "\"").body(file);
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
public int 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-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 handle(HttpServletRequest request, final HttpServletResponse response)
throws Exception
{
// We're sending an XML response, so set the response content type to text/xml
response.setContentType("text/xml");
// Parse the incoming request as XML
SAXReader xmlReader = new SAXReader();
Document doc = xmlReader.read(request.getInputStream());
Element env = doc.getRootElement();
final List<PollRequest> polls = unmarshalRequests(env);
new ContextualHttpServletRequest(request)
{
@Override
public void process() throws Exception
{
for (PollRequest req : polls)
{
req.poll();
}
// Package up the response
marshalResponse(polls, response.getOutputStream());
}
}.run();
} | 0 | Java | CWE-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 |
protected FrameHeaderData parseFrame(ByteBuffer data) throws IOException {
if (prefaceCount < PREFACE_BYTES.length) {
while (data.hasRemaining() && prefaceCount < PREFACE_BYTES.length) {
if (data.get() != PREFACE_BYTES[prefaceCount]) {
IoUtils.safeClose(getUnderlyingConnection());
throw UndertowMessages.MESSAGES.incorrectHttp2Preface();
}
prefaceCount++;
}
}
Http2FrameHeaderParser frameParser = this.frameParser;
if (frameParser == null) {
this.frameParser = frameParser = new Http2FrameHeaderParser(this, continuationParser);
this.continuationParser = null;
}
if (!frameParser.handle(data)) {
return null;
}
if (!initialSettingsReceived) {
if (frameParser.type != FRAME_TYPE_SETTINGS) {
UndertowLogger.REQUEST_IO_LOGGER.remoteEndpointFailedToSendInitialSettings(frameParser.type);
//StringBuilder sb = new StringBuilder();
//while (data.hasRemaining()) {
// sb.append((char)data.get());
// sb.append(" ");
//}
markReadsBroken(new IOException());
} else {
initialSettingsReceived = true;
}
}
this.frameParser = null;
if (frameParser.getActualLength() > receiveMaxFrameSize && frameParser.getActualLength() > unackedReceiveMaxFrameSize) {
sendGoAway(ERROR_FRAME_SIZE_ERROR);
throw UndertowMessages.MESSAGES.http2FrameTooLarge();
}
if (frameParser.getContinuationParser() != null) {
this.continuationParser = frameParser.getContinuationParser();
return null;
}
return frameParser;
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
for (final ReservedChar reservedChar : ReservedChar.values()) {
RAW_CHAR_TO_MARKER[reservedChar.rawChar] = reservedChar.marker;
MARKER_TO_PERCENT_ENCODED_CHAR[reservedChar.marker] = reservedChar.percentEncodedChar;
} | 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 byte[] engineGetEncoded()
{
try
{
ASN1EncodableVector v = new ASN1EncodableVector();
if (currentSpec.getDerivationV() != null)
{
v.add(new DERTaggedObject(false, 0, new DEROctetString(currentSpec.getDerivationV())));
}
if (currentSpec.getEncodingV() != null)
{
v.add(new DERTaggedObject(false, 1, new DEROctetString(currentSpec.getEncodingV())));
}
v.add(new ASN1Integer(currentSpec.getMacKeySize()));
if (currentSpec.getNonce() != null)
{
ASN1EncodableVector cV = new ASN1EncodableVector();
cV.add(new ASN1Integer(currentSpec.getCipherKeySize()));
cV.add(new ASN1Integer(currentSpec.getNonce()));
v.add(new DERSequence(cV));
}
return new DERSequence(v).getEncoded(ASN1Encoding.DER);
}
catch (IOException e)
{
throw new RuntimeException("Error encoding IESParameters");
}
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
public boolean match( final String pattern,
final String path ) {
return doMatch( pattern, path, true );
} | 1 | Java | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
private void ensureInitialized() throws SQLException {
if (!initialized) {
throw new PSQLException(
GT.tr(
"This SQLXML object has not been initialized, so you cannot retrieve data from it."),
PSQLState.OBJECT_NOT_IN_STATE);
}
// Is anyone loading data into us at the moment?
if (!active) {
return;
}
if (byteArrayOutputStream != null) {
try {
data = conn.getEncoding().decode(byteArrayOutputStream.toByteArray());
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Failed to convert binary xml data to encoding: {0}.",
conn.getEncoding().name()), PSQLState.DATA_ERROR, ioe);
} finally {
byteArrayOutputStream = null;
active = false;
}
} else if (stringWriter != null) {
// This is also handling the work for Stream, SAX, and StAX Results
// as they will use the same underlying stringwriter variable.
//
data = stringWriter.toString();
stringWriter = null;
active = false;
} else if (domResult != null) {
// Copy the content from the result to a source
// and use the identify transform to get it into a
// friendlier result format.
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource domSource = new DOMSource(domResult.getNode());
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
transformer.transform(domSource, streamResult);
data = stringWriter.toString();
} catch (TransformerException te) {
throw new PSQLException(GT.tr("Unable to convert DOMResult SQLXML data to a string."),
PSQLState.DATA_ERROR, te);
} finally {
domResult = null;
active = false;
}
}
} | 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 ECIESwithAES()
{
super(new AESEngine());
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
public void preflightCheck() {
String origin = "http://bla.com";
String headers ="X-Data: Test";
expect(backend.isCorsAccessAllowed(origin)).andReturn(true);
replay(backend);
Map<String,String> ret = handler.handleCorsPreflightRequest(origin, headers);
assertEquals(ret.get("Access-Control-Allow-Origin"),origin);
} | 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 testSelectByOperationsNotSpecifiedOrSign() {
JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyOperations(KeyOperation.SIGN, null).build());
List<JWK> keyList = new ArrayList<>();
keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.SIGN))).build());
keyList.add(new ECKey.Builder(ECKey.Curve.P_256, EC_P256_X, EC_P256_Y).keyID("2").build());
keyList.add(new ECKey.Builder(ECKey.Curve.P_256, EC_P256_X, EC_P256_Y).keyID("3")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.ENCRYPT))).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());
ECKey key2 = (ECKey)matches.get(1);
assertEquals(KeyType.EC, key2.getKeyType());
assertEquals("2", key2.getKeyID());
assertEquals(2, matches.size());
} | 1 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | safe |
public 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 Cipher encrypt() {
try {
Cipher cipher = Secret.getCipher(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, getKey());
return cipher;
} catch (GeneralSecurityException e) {
throw new AssertionError(e);
}
} | 1 | Java | CWE-326 | Inadequate Encryption Strength | The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required. | https://cwe.mitre.org/data/definitions/326.html | safe |
private ServletFileUpload getServletFileUpload() {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
return upload;
} | 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 static boolean isAbsolute(String url)
{
if (url.startsWith("//")) // //www.domain.com/start
{
return true;
}
if (url.startsWith("/")) // /somePage.html
{
return false;
}
boolean result = false;
try
{
URI uri = new URI(url);
result = uri.isAbsolute();
}
catch (URISyntaxException e) {} //Ignore
return result;
} | 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 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-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
private static PathAndQuery splitPathAndQuery(@Nullable final String pathAndQuery) {
final Bytes path;
final Bytes query;
if (pathAndQuery == null) {
return ROOT_PATH_QUERY;
}
// Split by the first '?'.
final int queryPos = pathAndQuery.indexOf('?');
if (queryPos >= 0) {
if ((path = decodePercentsAndEncodeToUtf8(
pathAndQuery, 0, queryPos, true)) == null) {
return null;
}
if ((query = decodePercentsAndEncodeToUtf8(
pathAndQuery, queryPos + 1, pathAndQuery.length(), false)) == null) {
return null;
}
} else {
if ((path = decodePercentsAndEncodeToUtf8(
pathAndQuery, 0, pathAndQuery.length(), true)) == null) {
return null;
}
query = null;
}
if (path.data[0] != '/' || path.isEncoded(0)) {
// Do not accept a relative path.
return null;
}
// Reject the prohibited patterns.
if (pathContainsDoubleDots(path) || queryContainsDoubleDots(query)) {
return null;
}
return new PathAndQuery(encodePathToPercents(path), encodeQueryToPercents(query));
} | 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 testInvalidData() throws IOException {
Map<String, String> invalidData = new HashMap();
invalidData.put("foo", "bar");
NamedTemporaryFile tempFile = new NamedTemporaryFile("invalid_parser_data", null);
try (FileOutputStream fos = new FileOutputStream(tempFile.get().toString());
ZipOutputStream zipos = new ZipOutputStream(fos)) {
zipos.putNextEntry(new ZipEntry("parser_data"));
try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) {
oos.writeObject(invalidData);
}
}
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp);
workspace.setUp();
// Load the invalid parser cache data.
thrown.expect(InvalidClassException.class);
thrown.expectMessage("Can't deserialize this class");
workspace.runBuckCommand("parser-cache", "--load", tempFile.get().toString());
} | 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 resetHandlers() {
getDispatchHandler().resetHandlers();
} | 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 Process execute()
throws CommandLineException
{
// TODO: Provided only for backward compat. with <= 1.4
verifyShellState();
Process process;
//addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );
String[] environment = getEnvironmentVariables();
File workingDir = shell.getWorkingDirectory();
try
{
if ( workingDir == null )
{
process = Runtime.getRuntime().exec( getShellCommandline(), environment );
}
else
{
if ( !workingDir.exists() )
{
throw new CommandLineException( "Working directory \"" + workingDir.getPath()
+ "\" does not exist!" );
}
else if ( !workingDir.isDirectory() )
{
throw new CommandLineException( "Path \"" + workingDir.getPath()
+ "\" does not specify a directory." );
}
process = Runtime.getRuntime().exec( getShellCommandline(), environment, workingDir );
}
}
catch ( IOException ex )
{
throw new CommandLineException( "Error while executing process.", ex );
}
return process;
} | 0 | Java | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters
.Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest)))
.withIndex(xmssMtPrivateKey.getIndex())
.withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed())
.withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF())
.withPublicSeed(xmssMtPrivateKey.getPublicSeed())
.withRoot(xmssMtPrivateKey.getRoot());
if (xmssMtPrivateKey.getBdsState() != null)
{
keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState(), BDSStateMap.class));
}
this.keyParams = keyBuilder.build();
}
catch (ClassNotFoundException e)
{
throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
}
} | 1 | Java | CWE-470 | Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') | The application uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code. | https://cwe.mitre.org/data/definitions/470.html | safe |
public void testPrivateKeySerialisation()
throws Exception
{
String stream = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArO0ABXNyACJzdW4ucm1pLnNlcnZlci5BY3RpdmF0aW9uR3JvdXBJbXBsT+r9SAwuMqcCAARaAA1ncm91cEluYWN0aXZlTAAGYWN0aXZldAAVTGphdmEvdXRpbC9IYXNodGFibGU7TAAHZ3JvdXBJRHQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Hcm91cElEO0wACWxvY2tlZElEc3QAEExqYXZhL3V0aWwvTGlzdDt4cgAjamF2YS5ybWkuYWN0aXZhdGlvbi5BY3RpdmF0aW9uR3JvdXCVLvKwBSnVVAIAA0oAC2luY2FybmF0aW9uTAAHZ3JvdXBJRHEAfgACTAAHbW9uaXRvcnQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Nb25pdG9yO3hyACNqYXZhLnJtaS5zZXJ2ZXIuVW5pY2FzdFJlbW90ZU9iamVjdEUJEhX14n4xAgADSQAEcG9ydEwAA2NzZnQAKExqYXZhL3JtaS9zZXJ2ZXIvUk1JQ2xpZW50U29ja2V0RmFjdG9yeTtMAANzc2Z0AChMamF2YS9ybWkvc2VydmVyL1JNSVNlcnZlclNvY2tldEZhY3Rvcnk7eHIAHGphdmEucm1pLnNlcnZlci5SZW1vdGVTZXJ2ZXLHGQcSaPM5+wIAAHhyABxqYXZhLnJtaS5zZXJ2ZXIuUmVtb3RlT2JqZWN002G0kQxhMx4DAAB4cHcSABBVbmljYXN0U2VydmVyUmVmeAAAFbNwcAAAAAAAAAAAcHAAcHBw";
XMSSParameters params = new XMSSParameters(10, new SHA256Digest());
byte[] output = Base64.decode(new String(stream).getBytes("UTF-8"));
//Simple Exploit
try
{
new XMSSPrivateKeyParameters.Builder(params).withPrivateKey(output, params).build();
}
catch (IllegalArgumentException e)
{
assertTrue(e.getCause() instanceof IOException);
}
//Same Exploit other method
XMSS xmss2 = new XMSS(params, new SecureRandom());
xmss2.generateKeys();
byte[] publicKey = xmss2.exportPublicKey();
try
{
xmss2.importState(output, publicKey);
}
catch (IllegalArgumentException e)
{
assertTrue(e.getCause() instanceof IOException);
}
} | 1 | Java | CWE-470 | Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') | The application uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code. | https://cwe.mitre.org/data/definitions/470.html | safe |
public static XStream createXStreamInstanceForDBObjects() {
return new EnhancedXStream(true);
} | 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 |
void testEqualsInsertionOrderDifferentHeaderNames() {
final HttpHeadersBase h1 = newEmptyHeaders();
h1.add("a", "b");
h1.add("c", "d");
final HttpHeadersBase h2 = newEmptyHeaders();
h2.add("c", "d");
h2.add("a", "b");
assertThat(h1).isEqualTo(h2);
} | 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 |
@Test public void pathParametersAndPathTraversal() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path(value = "ping") String ping) {
return null;
}
}
assertMalformedRequest(Example.class, ".");
assertMalformedRequest(Example.class, "..");
assertThat(buildRequest(Example.class, "./a").url().encodedPath())
.isEqualTo("/foo/bar/.%2Fa/");
assertThat(buildRequest(Example.class, "a/.").url().encodedPath())
.isEqualTo("/foo/bar/a%2F./");
assertThat(buildRequest(Example.class, "a/..").url().encodedPath())
.isEqualTo("/foo/bar/a%2F../");
assertThat(buildRequest(Example.class, "../a").url().encodedPath())
.isEqualTo("/foo/bar/..%2Fa/");
assertThat(buildRequest(Example.class, "..\\..").url().encodedPath())
.isEqualTo("/foo/bar/..%5C../");
assertThat(buildRequest(Example.class, "%2E").url().encodedPath())
.isEqualTo("/foo/bar/%252E/");
assertThat(buildRequest(Example.class, "%2E%2E").url().encodedPath())
.isEqualTo("/foo/bar/%252E%252E/");
} | 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 onTurnEnded(TurnEndedEvent event) {
super.onTurnEnded(event);
final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();
if (out.contains("An error occurred during initialization")) {
messagedInitialization = true;
}
if (out.contains("java.lang.SecurityException:")) {
securityExceptionOccurred = true;
}
} | 1 | Java | CWE-862 | Missing Authorization | The software does not perform an authorization check when an actor attempts to access a resource or perform an action. | https://cwe.mitre.org/data/definitions/862.html | safe |
public void doesNotPrefixAliasedFunctionCallNameWithDots() {
String query = "SELECT AVG(m.price) AS m.avg FROM Magazine m";
Sort sort = new Sort("m.avg");
assertThat(applySorting(query, sort, "m"), endsWith("order by m.avg asc"));
} | 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 testRenameTo() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
final int totalByteCount = 4096;
byte[] bytes = new byte[totalByteCount];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ByteBuf content = Unpooled.wrappedBuffer(bytes);
test.setContent(content);
boolean succ = test.renameTo(tmpFile);
assertTrue(succ);
FileInputStream fis = new FileInputStream(tmpFile);
try {
byte[] buf = new byte[totalByteCount];
int count = 0;
int offset = 0;
int size = totalByteCount;
while ((count = fis.read(buf, offset, size)) > 0) {
offset += count;
size -= count;
if (offset >= totalByteCount || size <= 0) {
break;
}
}
assertArrayEquals(bytes, buf);
assertEquals(0, fis.available());
} finally {
fis.close();
}
} finally {
//release the ByteBuf in AbstractMemoryHttpData
test.delete();
}
} | 0 | Java | CWE-379 | Creation of Temporary File in Directory with Insecure Permissions | The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file. | https://cwe.mitre.org/data/definitions/379.html | vulnerable |
public String getSHA(String password) {
try {
// Static getInstance method is called with hashing SHA
MessageDigest md = MessageDigest.getInstance("SHA-256");
// digest() method called
// to calculate message digest of an input
// and return array of byte
byte[] messageDigest = md.digest(password.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashPass = no.toString(16);
while (hashPass.length() < 32) {
hashPass = "0" + hashPass;
}
return hashPass;
// For specifying wrong message digest algorithms
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
} | 0 | Java | CWE-759 | Use of a One-Way Hash without a Salt | The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software does not also use a salt as part of the input. | https://cwe.mitre.org/data/definitions/759.html | vulnerable |
int numEncodedBytes() {
return numEncodedBytes;
} | 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 |
protected void switchToConversationDoNotAppend(Contact contact, String body) {
Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
switchToConversationDoNotAppend(conversation, body);
} | 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 engineInit(
int opmode,
Key key,
SecureRandom random)
throws InvalidKeyException
{
try
{
engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
}
catch (InvalidAlgorithmParameterException e)
{
throw new IllegalArgumentException("can't handle supplied parameter spec");
}
} | 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 String extractCorsOrigin(String pOrigin) {
if (pOrigin != null) {
// Prevent HTTP response splitting attacks
String origin = pOrigin.replaceAll("[\\n\\r]*","");
if (backendManager.isCorsAccessAllowed(origin)) {
return "null".equals(origin) ? "*" : origin;
} else {
return null;
}
}
return null;
} | 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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
UserFactory.init();
} catch (Throwable e) {
throw new ServletException("AddNewUserServlet: Error initialising user factory." + e);
}
UserManager userFactory = UserFactory.getInstance();
String userID = request.getParameter("userID");
if (userID != null && userID.matches(".*[&<>\"`']+.*")) {
throw new ServletException("User ID must not contain any HTML markup.");
}
String password = request.getParameter("pass1");
boolean hasUser = false;
try {
hasUser = userFactory.hasUser(userID);
} catch (Throwable e) {
throw new ServletException("can't determine if user " + userID + " already exists in users.xml.", e);
}
if (hasUser) {
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/userGroupView/users/newUser.jsp?action=redo");
dispatcher.forward(request, response);
} else {
final Password pass = new Password();
pass.setEncryptedPassword(UserFactory.getInstance().encryptedPassword(password, true));
pass.setSalt(true);
final User newUser = new User();
newUser.setUserId(userID);
newUser.setPassword(pass);
final HttpSession userSession = request.getSession(false);
userSession.setAttribute("user.modifyUser.jsp", newUser);
// forward the request for proper display
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/userGroupView/users/modifyUser.jsp");
dispatcher.forward(request, response);
}
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new ECDSA5Test());
} | 1 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | safe |
private 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-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 String getLike() {
return "like";
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String filename = file.getFileName().toString();
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 |
private static SecretKey getKey() 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 IESCipher(IESEngine engine)
{
this.engine = engine;
this.ivLength = 0;
} | 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 void recipe() throws Exception {
super.recipe();
recipes.add(new Runner() {
@Override
public void setup(HudsonTestCase testCase, Annotation recipe) throws Exception {
}
@Override
public void decorateHome(HudsonTestCase testCase, File home) throws Exception {
if (getName().endsWith("testScanOnBoot")) {
// schedule a scan on boot
File f = new File(home, RekeySecretAdminMonitor.class.getName() + "/scanOnBoot");
f.getParentFile().mkdirs();
new FilePath(f).touch(0);
// and stage some data
putSomeOldData(home);
}
}
@Override
public void tearDown(HudsonTestCase testCase, Annotation recipe) throws Exception {
}
});
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void test_notLike_any() {
Entity from = from(Entity.class);
where(from.getCode()).notLike().any("test");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where entity_0.code not like '%test%'", select.getQuery());
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private void testModified()
throws Exception
{
ECNamedCurveParameterSpec namedCurve = ECNamedCurveTable.getParameterSpec("P-256");
org.bouncycastle.jce.spec.ECPublicKeySpec pubSpec = new org.bouncycastle.jce.spec.ECPublicKeySpec(namedCurve.getCurve().createPoint(PubX, PubY), namedCurve);
KeyFactory kFact = KeyFactory.getInstance("EC", "BC");
PublicKey pubKey = kFact.generatePublic(pubSpec);
Signature sig = Signature.getInstance("SHA256WithECDSA", "BC");
for (int i = 0; i != MODIFIED_SIGNATURES.length; i++)
{
sig.initVerify(pubKey);
sig.update(Strings.toByteArray("Hello"));
boolean failed;
try
{
failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i]));
System.err.println(ASN1Dump.dumpAsString(ASN1Primitive.fromByteArray(Hex.decode(MODIFIED_SIGNATURES[i]))));
}
catch (SignatureException e)
{
failed = true;
}
isTrue("sig verified when shouldn't: " + i, failed);
}
} | 1 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | safe |
private boolean updateUserPictureAndName(Profile showUser, String picture, String name) {
boolean updateProfile = false;
boolean updateUser = false;
User u = showUser.getUser();
if (CONF.avatarEditsEnabled() && !StringUtils.isBlank(picture)) {
updateProfile = avatarRepository.store(showUser, picture);
}
if (CONF.nameEditsEnabled() && !StringUtils.isBlank(name)) {
showUser.setName(name);
if (StringUtils.isBlank(showUser.getOriginalName())) {
showUser.setOriginalName(name);
}
if (!u.getName().equals(name)) {
u.setName(name);
updateUser = true;
}
updateProfile = true;
}
if (updateUser) {
utils.getParaClient().update(u);
}
return updateProfile;
} | 0 | Java | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
public void switchToConversationDoNotAppend(Conversation conversation, String text) {
switchToConversation(conversation, text, false, null, false, 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 String getLiteralExecutable()
{
return 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 EfficiencyStatement getUserEfficiencyStatementByCourseRepositoryEntry(RepositoryEntry courseRepoEntry, Identity identity){
UserEfficiencyStatementImpl s = getUserEfficiencyStatementFull(courseRepoEntry, identity);
if(s == null || s.getStatementXml() == null) {
return null;
}
return (EfficiencyStatement)xstream.fromXML(s.getStatementXml());
} | 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 int sharedKeyLength(final JWEAlgorithm alg, final EncryptionMethod enc)
throws JOSEException {
if (alg.equals(JWEAlgorithm.ECDH_ES)) {
int length = enc.cekBitLength();
if (length == 0) {
throw new JOSEException("Unsupported JWE encryption method " + enc);
}
return length;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A128KW)) {
return 128;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A192KW)) {
return 192;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A256KW)) {
return 256;
} else {
throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(
alg, ECDHCryptoProvider.SUPPORTED_ALGORITHMS));
}
} | 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 XMLFilter getXMLFilter() {
return xmlFilter;
} | 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 |
protected String getExecutionPreamble()
{
if ( getWorkingDirectoryAsString() == null )
{
return null;
}
String dir = getWorkingDirectoryAsString();
StringBuilder sb = new StringBuilder();
sb.append( "cd " );
sb.append( unifyQuotes( dir ) );
sb.append( " && " );
return sb.toString();
} | 0 | Java | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
public void simpleGetWithUnsupportedGetParameterMapCall() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
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.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameterMap()).andThrow(new UnsupportedOperationException(""));
Vector params = new Vector();
params.add("debug");
expect(request.getParameterNames()).andReturn(params.elements());
expect(request.getParameterValues("debug")).andReturn(new String[] {"false"});
}
},
getStandardResponseSetup());
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request,response);
servlet.doGet(request,response);
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 |
void routingResult() throws URISyntaxException {
final RoutingResultBuilder builder = RoutingResult.builder();
final RoutingResult routingResult = builder.path("/foo")
.query("bar=baz")
.rawParam("qux", "quux")
.negotiatedResponseMediaType(MediaType.JSON_UTF_8)
.build();
assertThat(routingResult.isPresent()).isTrue();
assertThat(routingResult.path()).isEqualTo("/foo");
assertThat(routingResult.query()).isEqualTo("bar=baz");
assertThat(routingResult.pathParams()).containsOnly(new SimpleEntry<>("qux", "quux"));
assertThat(routingResult.negotiatedResponseMediaType()).isSameAs(MediaType.JSON_UTF_8);
} | 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 test_like_endsWith() {
Entity from = from(Entity.class);
where(from.getCode()).like().endsWith("test");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where entity_0.code like :code_1", select.getQuery());
assertEquals("%test", select.getParameters().get("code_1"));
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public OldIESwithDESede()
{
super(new DESedeEngine());
} | 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 DataSource createNewDataSource(Map<String, ?> params) throws IOException {
String refName = (String) JNDI_REFNAME.lookUp(params);
try {
return (DataSource) GeoTools.getInitialContext().lookup(refName);
} catch (Exception e) {
throw new DataSourceException("Could not find the specified data source in JNDI", e);
}
} | 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 setPathSeparator( final String pathSeparator ) {
this.pathSeparator = pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR;
} | 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 |
BCDHPublicKey(
DHPublicKey key)
{
this.y = key.getY();
this.dhSpec = key.getParams();
this.dhPublicKey = new DHPublicKeyParameters(y, new DHParameters(dhSpec.getP(), dhSpec.getG()));
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
public void prefixesSingleNonAliasedFunctionCallRelatedSortProperty() {
String query = "SELECT AVG(m.price) AS avgPrice FROM Magazine m";
Sort sort = new Sort("someOtherProperty");
assertThat(applySorting(query, sort, "m"), endsWith("order by m.someOtherProperty asc"));
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
private static CharSequenceMap toLowercaseMap(Iterator<? extends CharSequence> valuesIter,
int arraySizeHint) {
final CharSequenceMap result = new CharSequenceMap(arraySizeHint);
while (valuesIter.hasNext()) {
final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase();
try {
int index = lowerCased.forEachByte(FIND_COMMA);
if (index != -1) {
int start = 0;
do {
result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);
start = index + 1;
} while (start < lowerCased.length() &&
(index = lowerCased.forEachByte(start,
lowerCased.length() - start, FIND_COMMA)) != -1);
result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);
} else {
result.add(lowerCased.trim(), EMPTY_STRING);
}
} catch (Exception e) {
// This is not expect to happen because FIND_COMMA never throws but must be caught
// because of the ByteProcessor interface.
throw new IllegalStateException(e);
}
}
return result;
} | 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 empty() {
final PathAndQuery res = parse(null);
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/");
assertThat(res.query()).isNull();
final PathAndQuery res2 = parse("");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/");
assertThat(res2.query()).isNull();
final PathAndQuery res3 = parse("?");
assertThat(res3).isNotNull();
assertThat(res3.path()).isEqualTo("/");
assertThat(res3.query()).isEqualTo("");
} | 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 final void testClosedArray() {
// Discovered by fuzzer with seed -Dfuzz.seed=df3b4778ce54d00a
assertSanitized("-1742461140214282", "\ufeff-01742461140214282]");
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private void checkParams()
{
if (vi == null)
{
throw new IllegalArgumentException("no layers defined.");
}
if (vi.length > 1)
{
for (int i = 0; i < vi.length - 1; i++)
{
if (vi[i] >= vi[i + 1])
{
throw new IllegalArgumentException(
"v[i] has to be smaller than v[i+1]");
}
}
}
else
{
throw new IllegalArgumentException(
"Rainbow needs at least 1 layer, such that v1 < v2.");
}
} | 1 | Java | CWE-470 | Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') | The application uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code. | https://cwe.mitre.org/data/definitions/470.html | safe |
private X509TrustManager createTrustManager() {
X509TrustManager trustManager = new X509TrustManager() {
/**
* {@InheritDoc}
*
* @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String)
*/
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
logger.trace("Skipping trust check on client certificate {}", string);
}
/**
* {@InheritDoc}
*
* @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String)
*/
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
logger.trace("Skipping trust check on server certificate {}", string);
}
/**
* {@InheritDoc}
*
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
public X509Certificate[] getAcceptedIssuers() {
logger.trace("Returning empty list of accepted issuers");
return null;
}
};
return trustManager;
} | 0 | Java | CWE-346 | Origin Validation Error | The software does not properly verify that the source of data or communication is valid. | https://cwe.mitre.org/data/definitions/346.html | vulnerable |
public RekeySecretAdminMonitor() throws IOException {
// if JENKINS_HOME existed <1.497, we need to offer rewrite
// this computation needs to be done and the value be captured,
// since $JENKINS_HOME/config.xml can be saved later before the user has
// actually rewritten XML files.
if (Jenkins.getInstance().isUpgradedFromBefore(new VersionNumber("1.496.*")))
needed.on();
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public NotLikeCondition(Type type, Selector selector, String toMatch) {
super(type, selector, toMatch);
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public CBC()
{
super(new CBCBlockCipher(new AESFastEngine()), 128);
} | 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 invalidExample() throws Exception {
assertThat(ConstraintViolations.format(validator.validate(new InvalidExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.containsExactlyInAnyOrder(
new LoggingEvent(
Level.ERROR,
"The method {} is annotated with @SelfValidation but does not have a single parameter of type {}",
InvalidExample.class.getMethod("validateFailAdditionalParameters", ViolationCollector.class, int.class),
ViolationCollector.class
),
new LoggingEvent(
Level.ERROR,
"The method {} is annotated with @SelfValidation but does not return void. It is ignored",
InvalidExample.class.getMethod("validateFailReturn", ViolationCollector.class)
),
new LoggingEvent(
Level.ERROR,
"The method {} is annotated with @SelfValidation but is not public",
InvalidExample.class.getDeclaredMethod("validateFailPrivate", ViolationCollector.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 |
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 static byte[] generateNonceIVPersonalizationString()
{
return Arrays.concatenate(Strings.toByteArray("Default"), Strings.toUTF8ByteArray(getVIMID()),
Pack.longToLittleEndian(Thread.currentThread().getId()), Pack.longToLittleEndian(System.currentTimeMillis()));
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
void addEncoded(byte b) {
if (encoded == null) {
encoded = new BitSet();
}
encoded.set(length);
data[length++] = b;
numEncodedBytes++;
} | 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 |
BCDHPublicKey(
BigInteger y,
DHParameterSpec dhSpec)
{
this.y = y;
this.dhSpec = dhSpec;
this.dhPublicKey = new DHPublicKeyParameters(y, new DHParameters(dhSpec.getP(), dhSpec.getG()));
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
public void testPrivateKeySerialisation()
throws Exception
{
String stream = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArO0ABXNyACJzdW4ucm1pLnNlcnZlci5BY3RpdmF0aW9uR3JvdXBJbXBsT+r9SAwuMqcCAARaAA1ncm91cEluYWN0aXZlTAAGYWN0aXZldAAVTGphdmEvdXRpbC9IYXNodGFibGU7TAAHZ3JvdXBJRHQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Hcm91cElEO0wACWxvY2tlZElEc3QAEExqYXZhL3V0aWwvTGlzdDt4cgAjamF2YS5ybWkuYWN0aXZhdGlvbi5BY3RpdmF0aW9uR3JvdXCVLvKwBSnVVAIAA0oAC2luY2FybmF0aW9uTAAHZ3JvdXBJRHEAfgACTAAHbW9uaXRvcnQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Nb25pdG9yO3hyACNqYXZhLnJtaS5zZXJ2ZXIuVW5pY2FzdFJlbW90ZU9iamVjdEUJEhX14n4xAgADSQAEcG9ydEwAA2NzZnQAKExqYXZhL3JtaS9zZXJ2ZXIvUk1JQ2xpZW50U29ja2V0RmFjdG9yeTtMAANzc2Z0AChMamF2YS9ybWkvc2VydmVyL1JNSVNlcnZlclNvY2tldEZhY3Rvcnk7eHIAHGphdmEucm1pLnNlcnZlci5SZW1vdGVTZXJ2ZXLHGQcSaPM5+wIAAHhyABxqYXZhLnJtaS5zZXJ2ZXIuUmVtb3RlT2JqZWN002G0kQxhMx4DAAB4cHcSABBVbmljYXN0U2VydmVyUmVmeAAAFbNwcAAAAAAAAAAAcHAAcHBw";
XMSSParameters params = new XMSSParameters(10, new SHA256Digest());
byte[] output = Base64.decode(new String(stream).getBytes("UTF-8"));
//Simple Exploit
try
{
new XMSSPrivateKeyParameters.Builder(params).withPrivateKey(output, params).build();
}
catch (IllegalArgumentException e)
{
assertTrue(e.getCause() instanceof IOException);
}
//Same Exploit other method
XMSS xmss2 = new XMSS(params, new SecureRandom());
xmss2.generateKeys();
byte[] publicKey = xmss2.exportPublicKey();
try
{
xmss2.importState(output, publicKey);
}
catch (IllegalArgumentException e)
{
assertTrue(e.getCause() instanceof IOException);
}
} | 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 performTest()
throws Exception
{
// testKeyConversion();
// testAdaptiveKeyConversion();
// decodeTest();
// testECDSA239bitPrime();
// testECDSA239bitBinary();
// testGeneration();
// testKeyPairGenerationWithOIDs();
// testNamedCurveParameterPreservation();
// testNamedCurveSigning();
// testBSI();
// testMQVwithHMACOnePass();
// testAlgorithmParameters();
testModified();
} | 1 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | safe |
private String templatePath() {
if (templatePath == null) {
String file = HgCommand.class.getResource("/hg.template").getFile();
try {
templatePath = URLDecoder.decode(new File(file).getAbsolutePath(), "UTF-8");
} catch (UnsupportedEncodingException e) {
templatePath = URLDecoder.decode(new File(file).getAbsolutePath());
}
}
return templatePath;
} | 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 ModalDialog wantsNotificationOnClose()
{
mainContainer.add(new AjaxEventBehavior("hidden") {
@Override
protected void onEvent(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
handleCloseEvent(target);
}
});
return this;
} | 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 switchToConversation(Conversation conversation, String text) {
switchToConversation(conversation, text, false, null, false);
} | 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 static Object deserialize(byte[] data, Class clazz)
throws IOException, ClassNotFoundException
{
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
Object obj = is.readObject();
if (is.available() != 0)
{
throw new IOException("unexpected data found at end of ObjectInputStream");
}
if (clazz.isInstance(obj))
{
return obj;
}
else
{
throw new IOException("unexpected class found in ObjectInputStream");
}
} | 1 | Java | CWE-470 | Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') | The application uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code. | https://cwe.mitre.org/data/definitions/470.html | safe |
public JpaOrder ignoreCase() {
return new JpaOrder(getDirection(), getProperty(), getNullHandling(), true, this.unsafe);
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
public void testBourneShellQuotingCharacters()
throws Exception
{
// { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')' };
// test with values http://steve-parker.org/sh/bourne.shtml Appendix B - Meta-characters and Reserved Words
Commandline commandline = new Commandline( newShell() );
commandline.setExecutable( "chmod" );
commandline.getShell().setQuotedArgumentsEnabled( true );
commandline.createArg().setValue( " " );
commandline.createArg().setValue( "|" );
commandline.createArg().setValue( "&&" );
commandline.createArg().setValue( "||" );
commandline.createArg().setValue( ";" );
commandline.createArg().setValue( ";;" );
commandline.createArg().setValue( "&" );
commandline.createArg().setValue( "()" );
commandline.createArg().setValue( "<" );
commandline.createArg().setValue( "<<" );
commandline.createArg().setValue( ">" );
commandline.createArg().setValue( ">>" );
commandline.createArg().setValue( "*" );
commandline.createArg().setValue( "?" );
commandline.createArg().setValue( "[" );
commandline.createArg().setValue( "]" );
commandline.createArg().setValue( "{" );
commandline.createArg().setValue( "}" );
commandline.createArg().setValue( "`" );
String[] lines = commandline.getShellCommandline();
System.out.println( Arrays.asList( lines ) );
assertEquals( "/bin/sh", lines[0] );
assertEquals( "-c", lines[1] );
assertEquals( "chmod ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'",
lines[2] );
} | 0 | Java | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
public void annotatedSubClassExample() {
assertThat(ConstraintViolations.format(validator.validate(new AnnotatedSubclassExample())))
.containsExactlyInAnyOrder(
FAILED_RESULT,
FAILED_RESULT + "subclass"
);
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 |
public void testInvalidUserIds() {
testInvalidUserId("John<b>Doe</b>",true);
testInvalidUserId("Jane'Doe'",true);
testInvalidUserId("John&Doe",true);
testInvalidUserId("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 setDocumentFactory(DocumentFactory documentFactory) {
this.factory = documentFactory;
} | 0 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | vulnerable |
void space() {
final PathAndQuery res = PathAndQuery.parse("/ ? ");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/%20");
assertThat(res.query()).isEqualTo("+");
final PathAndQuery res2 = PathAndQuery.parse("/%20?%20");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/%20");
assertThat(res2.query()).isEqualTo("+");
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
public void translate(ServerMultiBlockChangePacket packet, GeyserSession session) {
for (BlockChangeRecord record : packet.getRecords()) {
ChunkUtils.updateBlock(session, record.getBlock(), record.getPosition());
}
} | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.