code
stringlengths 12
2.05k
| label
int64 0
1
| programming_language
stringclasses 9
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
103
⌀ | description
stringlengths 36
1.23k
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
public void testLowerFunctionInCondition() {
Entity entity = from(Entity.class);
OnGoingLogicalCondition condition = condition(lower(entity.getCode()))
.like().any("test");
where(condition);
Query<Entity> select = select(entity);
assertEquals(
"select entity_0 from Entity entity_0 where ( lower(entity_0.code) like '%test%' )",
select.getQuery());
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public void createElementLT() {
DocumentHelper.createElement("element<name");
} | 1 | Java | CWE-91 | XML Injection (aka Blind XPath Injection) | The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system. | https://cwe.mitre.org/data/definitions/91.html | safe |
static SecretKey deriveSharedKey(final JWEHeader header,
final SecretKey Z,
final ConcatKDF concatKDF)
throws JOSEException {
final int sharedKeyLength = sharedKeyLength(header.getAlgorithm(), header.getEncryptionMethod());
// Set the alg ID for the concat KDF
AlgorithmMode algMode = resolveAlgorithmMode(header.getAlgorithm());
final String algID;
if (algMode == AlgorithmMode.DIRECT) {
// algID = enc
algID = header.getEncryptionMethod().getName();
} else if (algMode == AlgorithmMode.KW) {
// algID = alg
algID = header.getAlgorithm().getName();
} else {
throw new JOSEException("Unsupported JWE ECDH algorithm mode: " + algMode);
}
return concatKDF.deriveKey(
Z,
sharedKeyLength,
ConcatKDF.encodeDataWithLength(algID.getBytes(Charset.forName("ASCII"))),
ConcatKDF.encodeDataWithLength(header.getAgreementPartyUInfo()),
ConcatKDF.encodeDataWithLength(header.getAgreementPartyVInfo()),
ConcatKDF.encodeIntData(sharedKeyLength),
ConcatKDF.encodeNoData());
} | 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 void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable {
File file = File.createTempFile("netty-", ".tmp");
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
// Just drop the message.
}
});
cb.handler(new ChannelInboundHandlerAdapter());
Channel sc = sb.bind().sync().channel();
Channel cc = cb.connect(sc.localAddress()).sync().channel();
// Request file region which is bigger then the underlying file.
FileRegion region = new DefaultFileRegion(
new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024);
assertThat(cc.writeAndFlush(region).await().cause(), CoreMatchers.<Throwable>instanceOf(IOException.class));
cc.close().sync();
sc.close().sync();
} | 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 void localNameFail() {
QName.get("!element");
} | 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 |
private BigInteger validate(BigInteger y, DHParameters dhParams)
{
if (dhParams.getQ() != null)
{
if (BigInteger.ONE.equals(y.modPow(dhParams.getQ(), dhParams.getP())))
{
return y;
}
throw new IllegalArgumentException("Y value does not appear to be in correct group");
}
else
{
return y; // we can't validate without Q.
}
} | 0 | Java | CWE-320 | Key Management Errors | Weaknesses in this category are related to errors in the management of cryptographic keys. | https://cwe.mitre.org/data/definitions/320.html | vulnerable |
public String encodeForLdap(String input) {
if( input == null ) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case '\\':
sb.append("\\5c");
break;
case '*':
sb.append("\\2a");
break;
case '(':
sb.append("\\28");
break;
case ')':
sb.append("\\29");
break;
case '\0':
sb.append("\\00");
break;
default:
sb.append(c);
}
}
return sb.toString();
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl wContr, Translator trans) {
this.translator = trans;
this.folderComponent = fc;
this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath());
VFSContainer currentContainer = folderComponent.getCurrentContainer();
List<String> lockedFiles = hasLockedFiles(currentContainer, fileSelection);
if (lockedFiles.isEmpty()) {
String msg = trans.translate("del.confirm") + "<p>" + fileSelection.renderAsHtml() + "</p>";
// create dialog controller
dialogCtr = activateYesNoDialog(ureq, trans.translate("del.header"), msg, dialogCtr);
} else {
String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles);
List<String> buttonLabels = Collections.singletonList(trans.translate("ok"));
lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr);
}
return this;
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
public AbstractMobileListForm(final AbstractMobileListPage< ? , ? , ? > parentPage)
{
super(parentPage);
final String userPrefFilterKey = this.getClass().getSimpleName() + ".filter";
try {
filter = (F) parentPage.getUserPrefEntry(userPrefFilterKey);
} catch (final ClassCastException ex) {
log.info("Could not restore filter from user prefs (OK, probably new software release): " + userPrefFilterKey);
}
if (filter == null) {
filter = newFilter();
parentPage.putUserPrefEntry(userPrefFilterKey, filter, true);
}
csrfTokenHandler = new CsrfTokenHandler(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 static JpaSort unsafe(String... properties) {
return unsafe(Sort.DEFAULT_DIRECTION, properties);
} | 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 static boolean isTransparent(HColor back) {
if (back == TRANSPARENT) {
return true;
}
if (back instanceof HColorBackground && ((HColorBackground) back).getBack() == TRANSPARENT) {
return true;
}
if (back instanceof HColorSimple && ((HColorSimple) back).isTransparent()) {
return true;
}
return false;
} | 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 |
List<T> newInstancesFromHeteroList(StaplerRequest req, Object formData,
Collection<? extends Descriptor<T>> descriptors) throws FormException {
List<T> items = new ArrayList<T>();
if (formData!=null) {
for (Object o : JSONArray.fromObject(formData)) {
JSONObject jo = (JSONObject)o;
String kind = jo.getString("kind");
items.add(find(descriptors,kind).newInstance(req,jo));
}
}
return items;
} | 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 int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
byte[] ciphertext, int ciphertextOffset, int length)
throws ShortBufferException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (!haskey) {
// The key is not set yet - return the plaintext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
return length;
}
if (space < 16 || length > (space - 16))
throw new ShortBufferException();
setup(ad);
encryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
ghash.update(ciphertext, ciphertextOffset, length);
ghash.pad(ad != null ? ad.length : 0, length);
ghash.finish(ciphertext, ciphertextOffset + length, 16);
for (int index = 0; index < 16; ++index)
ciphertext[ciphertextOffset + length + index] ^= hashKey[index];
return length + 16;
} | 0 | Java | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
public static void copyDb(
String jdbcDriverSource,
String usernameSource,
String passwordSource,
String jdbcUrlSource,
String jdbcDriverTarget,
String usernameTarget,
String passwordTarget,
String jdbcUrlTarget,
List<String> includeDbObjects,
List<String> excludeDbObjects,
List<String> valuePatterns,
List<String> valueReplacements,
PrintStream out
) throws ServiceException {
{
DBOBJECTS.clear();
List<String> tableNames = new ArrayList<String>();
try {
tableNames = DbSchemaUtils.getTableNames();
} catch (Exception e) {
new ServiceException(e).log();
}
for(String tableName : tableNames) {
if(
tableName.indexOf("_") > 0 &&
tableName.indexOf("_TOBJ_") < 0 &&
tableName.indexOf("_JOIN_") < 0 &&
!tableName.endsWith("_")
) {
DBOBJECTS.add(tableName);
}
}
}
try {
// Source connection
Class.forName(jdbcDriverSource);
Properties props = new Properties();
props.put("user", usernameSource);
props.put("password", passwordSource);
Connection connSource = DriverManager.getConnection(jdbcUrlSource, props);
connSource.setAutoCommit(true);
// Target connection
Class.forName(jdbcDriverTarget);
props = new Properties();
props.put("user", usernameTarget);
props.put("password", passwordTarget);
Connection connTarget = DriverManager.getConnection(jdbcUrlTarget, props);
connTarget.setAutoCommit(true);
CopyDb.copyNamespace(
connSource,
connTarget,
filterDbObjects(
DBOBJECTS,
includeDbObjects,
excludeDbObjects
),
valuePatterns,
valueReplacements,
out
);
} catch (Exception e) {
throw new ServiceException(e);
}
out.println();
out.println("!!! DONE !!!");
} | 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 |
void setup()
{
this.saveAction = new SaveAction();
context = oldcore.getXWikiContext();
xWiki = mock(XWiki.class);
context.setWiki(this.xWiki);
mockRequest = mock(XWikiRequest.class);
context.setRequest(mockRequest);
mockResponse = mock(XWikiResponse.class);
context.setResponse(mockResponse);
mockDocument = mock(XWikiDocument.class);
context.setDoc(mockDocument);
mockClonedDocument = mock(XWikiDocument.class);
when(mockDocument.clone()).thenReturn(mockClonedDocument);
mockForm = mock(EditForm.class);
context.setForm(mockForm);
when(this.entityNameValidationConfiguration.useValidation()).thenReturn(false);
context.setUserReference(USER_REFERENCE);
} | 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 getEncryptedValue() {
try {
Cipher cipher = KEY.encrypt();
// add the magic suffix which works like a check sum.
return new String(Base64.encode(cipher.doFinal((value+MAGIC).getBytes("UTF-8"))));
} catch (GeneralSecurityException e) {
throw new Error(e); // impossible
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static boolean nameContainsForbiddenSequence(String name) {
boolean result = false;
if (name != null) {
name = name.toLowerCase();
result = name.startsWith(".") ||
name.contains("../") ||
name.contains("..\\") ||
name.startsWith("/") ||
name.startsWith("\\") ||
name.endsWith("/") ||
name.contains("..%2f") ||
name.contains("..%5c") ||
name.startsWith("%2f") ||
name.startsWith("%5c") ||
name.endsWith("%2f") ||
name.contains("..\\u002f") ||
name.contains("..\\u005c") ||
name.startsWith("\\u002f") ||
name.startsWith("\\u005c") ||
name.endsWith("\\u002f")
;
}
return result;
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
void requestResetPassword() throws Exception
{
when(this.userManager.exists(this.userReference)).thenReturn(true);
InternetAddress email = new InternetAddress("[email protected]");
when(this.userProperties.getEmail()).thenReturn(email);
BaseObject xObject = mock(BaseObject.class);
when(this.userDocument
.getXObject(DefaultResetPasswordManager.RESET_PASSWORD_REQUEST_CLASS_REFERENCE, true, this.context))
.thenReturn(xObject);
String verificationCode = "abcde1234";
when(this.xWiki.generateRandomString(30)).thenReturn(verificationCode);
when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.versionComment"))
.thenReturn("Save verification code 42");
ResetPasswordRequestResponse expectedResult =
new DefaultResetPasswordRequestResponse(this.userReference, email,
verificationCode);
assertEquals(expectedResult, this.resetPasswordManager.requestResetPassword(this.userReference));
verify(xObject).set(DefaultResetPasswordManager.VERIFICATION_PROPERTY, verificationCode, context);
verify(this.xWiki).saveDocument(this.userDocument, "Save verification code 42", true, this.context);
} | 0 | Java | CWE-640 | Weak Password Recovery Mechanism for Forgotten Password | The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak. | https://cwe.mitre.org/data/definitions/640.html | vulnerable |
public void testDirectContextUsage() {
assertThat(ConstraintViolations.format(validator.validate(new DirectContextExample())))
.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 hexadecimal() {
assertThat(parse("/%")).isNull();
assertThat(parse("/%0")).isNull();
assertThat(parse("/%0X")).isNull();
assertThat(parse("/%X0")).isNull();
} | 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 testDecodePath() throws Exception {
// Fast path
final String pathThatDoesNotNeedDecode = "/foo_bar_baz";
assertThat(decodePath(pathThatDoesNotNeedDecode)).isSameAs(pathThatDoesNotNeedDecode);
// Slow path
assertThat(decodePath("/foo%20bar\u007fbaz")).isEqualTo("/foo bar\u007fbaz");
assertThat(decodePath("/%C2%A2")).isEqualTo("/¢"); // Valid UTF-8 sequence
assertThat(decodePath("/%20\u0080")).isEqualTo("/ �"); // Unallowed character
assertThat(decodePath("/%")).isEqualTo("/�"); // No digit
assertThat(decodePath("/%1")).isEqualTo("/�"); // Only a single digit
assertThat(decodePath("/%G0")).isEqualTo("/�"); // First digit is not hex.
assertThat(decodePath("/%0G")).isEqualTo("/�"); // Second digit is not hex.
assertThat(decodePath("/%C3%28")).isEqualTo("/�("); // Invalid UTF-8 sequence
} | 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 subClassExample() {
assertThat(ConstraintViolations.format(validator.validate(new SubclassExample())))
.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 |
private void saveToFile(VFSLeaf glossaryFile, List<GlossaryItem> glossaryItemArr) {
// cdata-tags should be used instead of strings, overwrite writer.
glossaryItemArr = removeEmptyGlossaryItems(glossaryItemArr);
XStreamHelper.writeObject(xstreamWriter, glossaryFile, glossaryItemArr);
} | 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 |
private HColor getColor(ColorParam colorParam, Stereotype stereo) {
final ISkinParam skinParam = diagram.getSkinParam();
return rose.getHtmlColor(skinParam, stereo, colorParam);
} | 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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userID = request.getParameter("userID");
String newID = request.getParameter("newID");
if (newID != null && newID.matches(".*[&<>\"`']+.*")) {
throw new ServletException("User ID must not contain any HTML markup.");
}
// now save to the xml file
try {
UserManager userFactory = UserFactory.getInstance();
userFactory.renameUser(userID, newID);
} catch (Throwable e) {
throw new ServletException("Error renaming user " + userID + " to " + newID, e);
}
response.sendRedirect("list.jsp");
} | 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 testMatchOperationsNotSpecifiedOrSign() {
JWKMatcher matcher = new JWKMatcher.Builder().keyOperations(KeyOperation.SIGN, null).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.SIGN))).build()));
assertTrue(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("3")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.ENCRYPT))).build()));
assertEquals("key_ops=[sign, null]", 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 void shouldCloneFromRemoteRepo() {
assertThat(clientRepo.listFiles().length > 0, is(true));
} | 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 EnvVars getCharacteristicEnvVars() {
EnvVars env = new EnvVars();
env.put("JENKINS_SERVER_COOKIE",SERVER_COOKIE.get());
env.put("HUDSON_SERVER_COOKIE",SERVER_COOKIE.get()); // Legacy compatibility
env.put("JOB_NAME",getFullName());
return env;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void testCreateHttpUrlConnection() {
HttpURLConnection conn;
// Test without proxy
conn = createHttpUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
Assert.assertNotNull(conn);
// Test with the proxy
conn = createHttpUrlConnection(convertToUrl(TEST_URL), "http://localhost", 9090, "testUser", "testPassword");
Assert.assertNotNull(conn);
} | 0 | Java | CWE-306 | Missing Authentication for Critical Function | The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources. | https://cwe.mitre.org/data/definitions/306.html | vulnerable |
private void checkParams()
throws Exception
{
if (vi == null)
{
throw new Exception("no layers defined.");
}
if (vi.length > 1)
{
for (int i = 0; i < vi.length - 1; i++)
{
if (vi[i] >= vi[i + 1])
{
throw new Exception(
"v[i] has to be smaller than v[i+1]");
}
}
}
else
{
throw new Exception(
"Rainbow needs at least 1 layer, such that v1 < v2.");
}
} | 0 | Java | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
private ModelAndView addGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String groupName = request.getParameter("groupName");
String groupComment = request.getParameter("groupComment");
if (groupComment == null) {
groupComment = "";
}
if (groupName != null && groupName.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group ID must not contain any HTML markup.");
}
if (groupComment != null && groupComment.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group comment must not contain any HTML markup.");
}
boolean hasGroup = false;
try {
hasGroup = m_groupRepository.groupExists(groupName);
} catch (Throwable e) {
throw new ServletException("Can't determine if group " + groupName + " already exists in groups.xml.", e);
}
if (hasGroup) {
return new ModelAndView("admin/userGroupView/groups/newGroup", "action", "redo");
} else {
WebGroup newGroup = new WebGroup();
newGroup.setName(groupName);
newGroup.setComments(groupComment);
return editGroup(request, newGroup);
}
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
private void sendAllJSON(HttpExchange pExchange, ParsedUri pParsedUri, JSONAware pJson) throws IOException {
OutputStream out = null;
try {
Headers headers = pExchange.getResponseHeaders();
if (pJson != null) {
headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
String json = pJson.toJSONString();
String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
String content = callback != null && MimeTypeUtil.isValidCallback(callback) ? callback + "(" + json + ");" : json;
byte[] response = content.getBytes("UTF8");
pExchange.sendResponseHeaders(200,response.length);
out = pExchange.getResponseBody();
out.write(response);
} else {
headers.set("Content-Type", "text/plain");
pExchange.sendResponseHeaders(200,-1);
}
} finally {
if (out != null) {
// Always close in order to finish the request.
// Otherwise the thread blocks.
out.close();
}
}
} | 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 testWhereWithLikeFunction() {
Entity from = from(Entity.class);
where(lower(from.getCode())).like("%test%");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where lower(entity_0.code) like '%test%'", select.getQuery());
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}
} | 0 | Java | CWE-306 | Missing Authentication for Critical Function | The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources. | https://cwe.mitre.org/data/definitions/306.html | vulnerable |
public MultiMap add(CharSequence name, CharSequence value) {
HttpUtils.validateHeader(name, value);
headers.add(toLowerCase(name), value);
return this;
} | 1 | Java | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
protected boolean evaluate(InputSource inputSource)
{
try
{
DocumentBuilder dbuilder = createDocumentBuilder();
Document doc = dbuilder.parse(inputSource);
//An XPath expression could return a true or false value instead of a node.
//eval() is a better way to determine the boolean value of the exp.
//For compliance with legacy behavior where selecting an empty node returns true,
//selectNodeIterator is attempted in case of a failure.
CachedXPathAPI cachedXPathAPI = new CachedXPathAPI();
XObject result = cachedXPathAPI.eval(doc, xpath);
if (result.bool())
return true;
else
{
NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath);
return (iterator.nextNode() != null);
}
}
catch (Throwable e)
{
return false;
}
} | 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 checkAccess(Thread t) {
if (RobocodeProperties.isSecurityOff()) {
return;
}
Thread c = Thread.currentThread();
if (isSafeThread(c)) {
return;
}
super.checkAccess(t);
// Threads belonging to other thread groups is not allowed to access threads belonging to other thread groups
// Bug fix [3021140] Possible for robot to kill other robot threads.
// In the following the thread group of the current thread must be in the thread group hierarchy of the
// attacker thread; otherwise an AccessControlException must be thrown.
boolean found = false;
ThreadGroup cg = c.getThreadGroup();
ThreadGroup tg = t.getThreadGroup();
while (tg != null) {
if (tg == cg) {
found = true;
break;
}
try {
tg = tg.getParent();
} catch (AccessControlException e) {
// We expect an AccessControlException due to missing RuntimePermission modifyThreadGroup
break;
}
}
if (!found) {
String message = "Preventing " + c.getName() + " from access to " + t.getName();
IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);
if (robotProxy != null) {
robotProxy.punishSecurityViolation(message);
}
throw new AccessControlException(message);
}
} | 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 |
private String deflateAndEncode(byte[] result) {
Deflater deflater = new Deflater(Deflater.DEFLATED, true);
deflater.setInput(result);
deflater.finish();
byte[] deflatedResult = new byte[result.length];
int length = deflater.deflate(deflatedResult);
deflater.end();
byte[] src = Arrays.copyOf(deflatedResult, length);
return Base64.getEncoder().encodeToString(src);
} | 0 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | vulnerable |
public static String applySorting(String query, Sort sort, String alias) {
Assert.hasText(query);
if (null == sort || !sort.iterator().hasNext()) {
return query;
}
StringBuilder builder = new StringBuilder(query);
if (!ORDER_BY.matcher(query).matches()) {
builder.append(" order by ");
} else {
builder.append(", ");
}
Set<String> aliases = getOuterJoinAliases(query);
Set<String> functionAliases = getFunctionAliases(query);
for (Order order : sort) {
builder.append(getOrderClause(aliases, functionAliases, alias, order)).append(", ");
}
builder.delete(builder.length() - 2, builder.length());
return builder.toString();
} | 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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userID = request.getParameter("userID");
String newID = request.getParameter("newID");
if (newID != null && newID.matches(".*[&<>\"`']+.*")) {
throw new ServletException("User ID must not contain any HTML markup.");
}
// now save to the xml file
try {
UserManager userFactory = UserFactory.getInstance();
userFactory.renameUser(userID, newID);
} catch (Throwable e) {
throw new ServletException("Error renaming user " + userID + " to " + newID, e);
}
response.sendRedirect("list.jsp");
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
public int hashCode()
{
return new HashCodeBuilder(17, 37)
.append(userReference)
.append(userEmail)
.append(verificationCode)
.toHashCode();
} | 0 | Java | CWE-640 | Weak Password Recovery Mechanism for Forgotten Password | The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak. | https://cwe.mitre.org/data/definitions/640.html | vulnerable |
public Operation.OperationResult executeFixedCostOperation(
final MessageFrame frame, final EVM evm) {
Bytes shiftAmount = frame.popStackItem();
if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {
frame.popStackItem();
frame.pushStackItem(UInt256.ZERO);
} else {
final int shiftAmountInt = shiftAmount.toInt();
final Bytes value = leftPad(frame.popStackItem());
if (shiftAmountInt >= 256) {
frame.pushStackItem(UInt256.ZERO);
} else {
frame.pushStackItem(value.shiftRight(shiftAmountInt));
}
}
return successResponse;
} | 0 | Java | CWE-681 | Incorrect Conversion between Numeric Types | When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur. | https://cwe.mitre.org/data/definitions/681.html | vulnerable |
public void existingDocumentTerminalFromUI() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Submit from the UI spaceReference=X&name=Y&tocreate=terminal
when(mockRequest.getParameter("spaceReference")).thenReturn("X");
when(mockRequest.getParameter("name")).thenReturn("Y");
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 instead of X.Y.WebHome because the tocreate parameter says "terminal".
verify(mockURLFactory).createURL("X", "Y", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki",
context);
} | 0 | Java | CWE-862 | Missing Authorization | The software does not perform an authorization check when an actor attempts to access a resource or perform an action. | https://cwe.mitre.org/data/definitions/862.html | vulnerable |
public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
return new AuthorizationCodeTokenRequest(transport, jsonFactory,
new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication(
clientAuthentication).setRequestInitializer(requestInitializer).setScopes(scopes);
} | 0 | Java | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
.Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))
.withIndex(xmssPrivateKey.getIndex())
.withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())
.withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())
.withPublicSeed(xmssPrivateKey.getPublicSeed())
.withRoot(xmssPrivateKey.getRoot());
if (xmssPrivateKey.getBdsState() != null)
{
keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));
}
this.keyParams = keyBuilder.build();
}
catch (ClassNotFoundException e)
{
throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
}
} | 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 <T> T withEncodedPassword(AuthenticationRequestType type, Properties info,
PasswordAction<byte[], T> action) throws PSQLException, IOException {
byte[] encodedPassword = withPassword(type, info, password -> {
if (password == null) {
throw new PSQLException(
GT.tr("The server requested password-based authentication, but no password was provided."),
PSQLState.CONNECTION_REJECTED);
}
ByteBuffer buf = StandardCharsets.UTF_8.encode(CharBuffer.wrap(password));
byte[] bytes = new byte[buf.limit()];
buf.get(bytes);
return bytes;
});
try {
return action.apply(encodedPassword);
} finally {
java.util.Arrays.fill(encodedPassword, (byte) 0);
}
} | 0 | Java | CWE-665 | Improper Initialization | The software does not initialize or incorrectly initializes a resource, which might leave the resource in an unexpected state when it is accessed or used. | https://cwe.mitre.org/data/definitions/665.html | vulnerable |
private void testHeaderNameEndsWithControlChar(int controlChar) {
ByteBuf requestBuffer = Unpooled.buffer();
requestBuffer.writeCharSequence("GET /some/path HTTP/1.1\r\n" +
"Host: netty.io\r\n", CharsetUtil.US_ASCII);
requestBuffer.writeCharSequence("Transfer-Encoding", CharsetUtil.US_ASCII);
requestBuffer.writeByte(controlChar);
requestBuffer.writeCharSequence(": chunked\r\n\r\n", CharsetUtil.US_ASCII);
testInvalidHeaders0(requestBuffer);
} | 1 | Java | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
public void removeHandler(String path) {
getDispatchHandler().removeHandler(path);
} | 0 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | vulnerable |
public void testStringFilterInjection() throws Exception {
DataSet result = dataSetManager.lookupDataSet(
DataSetLookupFactory.newDataSetLookupBuilder()
.dataset(DataSetGroupTest.EXPENSE_REPORTS)
.filter(COLUMN_EMPLOYEE, FilterFactory.equalsTo("David' OR EMPLOYEE != 'Toni"))
.buildLookup());
assertEquals(result.getRowCount(), 0);
result = dataSetManager.lookupDataSet(
DataSetLookupFactory.newDataSetLookupBuilder()
.dataset(DataSetGroupTest.EXPENSE_REPORTS)
.filter(COLUMN_EMPLOYEE, FilterFactory.equalsTo("David\" OR EMPLOYEE != \"Toni"))
.buildLookup());
assertEquals(result.getRowCount(), 0);
result = dataSetManager.lookupDataSet(
DataSetLookupFactory.newDataSetLookupBuilder()
.dataset(DataSetGroupTest.EXPENSE_REPORTS)
.filter(COLUMN_EMPLOYEE, FilterFactory.equalsTo("David` OR EMPLOYEE != `Toni"))
.buildLookup());
assertEquals(result.getRowCount(), 0);
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
protected DataSource createDataSource() throws SQLException {
InitialContext context = null;
DataSource source = null;
try {
context = GeoTools.getInitialContext();
source = (DataSource) context.lookup(datasourceName);
} catch (IllegalArgumentException | NoInitialContextException exception) {
// Fall back on 'return null' below.
} catch (NamingException exception) {
registerInto = context;
// Fall back on 'return null' below.
}
return source;
} | 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 testInvalidGroupIds() {
testInvalidGroupId("John<b>Doe</b>",true);
testInvalidGroupId("Jane'Doe'",true);
testInvalidGroupId("John&Doe",true);
testInvalidGroupId("Jane\"\"Doe",true);
} | 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 |
void semicolon() {
final PathAndQuery res = parse("/;?a=b;c=d");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/;");
assertThat(res.query()).isEqualTo("a=b;c=d");
// '%3B' in a query string should never be decoded into ';'.
final PathAndQuery res2 = parse("/%3b?a=b%3Bc=d");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/;");
assertThat(res2.query()).isEqualTo("a=b%3Bc=d");
} | 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 onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException {
super.onSuccessfulAuthentication(request,response,authResult);
// make sure we have a session to store this successful authentication, given that we no longer
// let HttpSessionContextIntegrationFilter2 to create sessions.
// HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later
// (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its
// doFilter method.
request.getSession().invalidate();
request.getSession();
} | 1 | Java | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
public int getPosition()
{
if ( realPos == -1 )
{
realPos = ( getLiteralExecutable() == null ? 0 : 1 );
for ( int i = 0; i < position; i++ )
{
Arg arg = (Arg) arguments.elementAt( i );
realPos += arg.getParts().length;
}
}
return realPos;
} | 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 |
private static void appendHexNibble(StringBuilder buf, int nibble) {
if (nibble < 10) {
buf.append((char) ('0' + nibble));
} else {
buf.append((char) ('A' + nibble - 10));
}
} | 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 zipFolderAPKTool(String srcFolder, String destZipFile) throws Exception {
try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
ZipOutputStream zip = new ZipOutputStream(fileWriter)){
addFolderToZipAPKTool("", srcFolder, zip);
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 |
private Secret(String value) {
this.value = value;
} | 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 static Archive<?> createTestArchive1()
{
WebArchive war = ShrinkWrap.create(WebArchive.class, "RESTEASY-1073-expand.war")
.addClasses(TestApplication.class)
.addClasses(TestResource.class, TestWrapper.class)
.addAsWebInfResource("web_expand.xml", "web.xml")
;
System.out.println(war.toString(true));
return war;
}
| 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 |
private ModelAndView addGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String groupName = request.getParameter("groupName");
String groupComment = request.getParameter("groupComment");
if (groupComment == null) {
groupComment = "";
}
if (groupName != null && groupName.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group ID must not contain any HTML markup.");
}
if (groupComment != null && groupComment.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group comment must not contain any HTML markup.");
}
boolean hasGroup = false;
try {
hasGroup = m_groupRepository.groupExists(groupName);
} catch (Throwable e) {
throw new ServletException("Can't determine if group " + groupName + " already exists in groups.xml.", e);
}
if (hasGroup) {
return new ModelAndView("admin/userGroupView/groups/newGroup", "action", "redo");
} else {
WebGroup newGroup = new WebGroup();
newGroup.setName(groupName);
newGroup.setComments(groupComment);
return editGroup(request, newGroup);
}
} | 1 | Java | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
public static Map<String, String> genHeaderMapByRequest(HttpServletRequest request) {
Map<String, String> map = new HashMap<>();
AdminTokenVO adminTokenVO = AdminTokenThreadLocal.getUser();
if (adminTokenVO != null) {
User user = User.dao.findById(adminTokenVO.getUserId());
map.put("LoginUserName", user.get("userName").toString());
map.put("LoginUserId", adminTokenVO.getUserId() + "");
}
map.put("IsLogin", (adminTokenVO != null) + "");
map.put("Current-Locale", I18nUtil.getCurrentLocale());
map.put("Blog-Version", ((Map) JFinal.me().getServletContext().getAttribute("zrlog")).get("version").toString());
if (request != null) {
String fullUrl = ZrLogUtil.getFullUrl(request);
if (request.getQueryString() != null) {
fullUrl = fullUrl + "?" + request.getQueryString();
}
if (adminTokenVO != null) {
fullUrl = adminTokenVO.getProtocol() + ":" + fullUrl;
}
map.put("Cookie", request.getHeader("Cookie"));
map.put("AccessUrl", "http://127.0.0.1:" + request.getServerPort() + request.getContextPath());
if (request.getHeader("Content-Type") != null) {
map.put("Content-Type", request.getHeader("Content-Type"));
}
map.put("Full-Url", fullUrl);
}
return map;
} | 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 |
private static byte[] generateDefaultPersonalizationString()
{
return Arrays.concatenate(Strings.toByteArray("Default"), Strings.toUTF8ByteArray(getVIMID()),
Pack.longToBigEndian(Thread.currentThread().getId()), Pack.longToBigEndian(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 |
MapEntry() {
this.hash = -1;
this.key = null;
this.value = null;
} | 1 | Java | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
public boolean verify(final String host, final String certHostname) {
try {
matchCN(host, certHostname, this.publicSuffixMatcher);
return true;
} catch (SSLException ex) {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, ex.getMessage(), ex);
}
return false;
}
} | 1 | Java | CWE-755 | Improper Handling of Exceptional Conditions | The software does not handle or incorrectly handles an exceptional condition. | https://cwe.mitre.org/data/definitions/755.html | safe |
void encodedUnicode() {
final String encodedPath = "/%ec%95%88";
final String encodedQuery = "%eb%85%95";
final PathAndQuery res = parse(encodedPath + '?' + encodedQuery);
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo(Ascii.toUpperCase(encodedPath));
assertThat(res.query()).isEqualTo(Ascii.toUpperCase(encodedQuery));
} | 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 traceLdapEnv(Properties env)
{
if (trace)
{
Properties tmp = new Properties();
tmp.putAll(env);
String credentials = tmp.getProperty(Context.SECURITY_CREDENTIALS);
String bindCredential = tmp.getProperty(BIND_CREDENTIAL);
if (credentials != null && credentials.length() > 0) {
tmp.setProperty(Context.SECURITY_CREDENTIALS, "***");
}
if (bindCredential != null && bindCredential.length() > 0) {
tmp.setProperty(BIND_CREDENTIAL, "***");
}
log.trace("Logging into LDAP server, env=" + tmp.toString());
}
} | 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 |
protected void handleCloseEvent(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
} | 1 | Java | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
private static PathAndQuery parse(@Nullable String rawPath) {
final PathAndQuery res = PathAndQuery.parse(rawPath);
if (res != null) {
logger.info("parse({}) => path: {}, query: {}", rawPath, res.path(), res.query());
} else {
logger.info("parse({}) => null", rawPath);
}
return res;
} | 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 parseModuleConfigFile(Digester digester, String path)
throws UnavailableException {
InputStream input = null;
try {
URL url = getServletContext().getResource(path);
// If the config isn't in the servlet context, try the class loader
// which allows the config files to be stored in a jar
if (url == null) {
url = getClass().getResource(path);
}
if (url == null) {
String msg = internal.getMessage("configMissing", path);
log.error(msg);
throw new UnavailableException(msg);
}
InputSource is = new InputSource(url.toExternalForm());
input = url.openStream();
is.setByteStream(input);
digester.parse(is);
} catch (MalformedURLException e) {
handleConfigException(path, e);
} catch (IOException e) {
handleConfigException(path, e);
} catch (SAXException e) {
handleConfigException(path, e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
throw new UnavailableException(e.getMessage());
}
}
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
protected BigInteger[] derDecode(
byte[] encoding)
throws IOException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);
ASN1InputStream aIn = new ASN1InputStream(bIn);
ASN1Sequence s = (ASN1Sequence)aIn.readObject();
BigInteger[] sig = new BigInteger[2];
sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue();
sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue();
return sig;
} | 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 String mac(String message) {
try {
return Util.toHexString(mac(message.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
} | 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];
if (b3 == '/' && b2 == '.' && b1 == '.' && b0 == '/') {
return true;
}
b0 = b1;
b1 = b2;
b2 = b3;
}
return b0 == '/' && b1 == '.' && b2 == '.';
} | 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 Descriptor find(String className) {
return find(Jenkins.getInstance().getExtensionList(Descriptor.class),className);
} | 0 | Java | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | vulnerable |
public void translate(ServerSpawnPlayerPacket packet, GeyserSession session) {
Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getYaw());
PlayerEntity entity;
if (packet.getUuid().equals(session.getPlayerEntity().getUuid())) {
// Server is sending a fake version of the current player
entity = new PlayerEntity(session.getPlayerEntity().getProfile(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), position, Vector3f.ZERO, rotation);
} else {
entity = session.getEntityCache().getPlayerEntity(packet.getUuid());
if (entity == null) {
GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.entity.player.failed_list", packet.getUuid()));
return;
}
entity.setEntityId(packet.getEntityId());
entity.setPosition(position);
entity.setRotation(rotation);
}
session.getEntityCache().cacheEntity(entity);
entity.sendPlayer(session);
SkinManager.requestAndHandleSkinAndCape(entity, session, null);
} | 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 Claims validateToken(String token) throws AuthenticationException {
try {
RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();
PublicKey publicKey = rsaKeyUtil.fromPemEncoded(keycloakPublicKey);
return (Claims) Jwts.parser().setSigningKey(publicKey).parse(token.replace("Bearer ", "")).getBody();
} catch (Exception e){
throw new AuthenticationException(String.format("Failed to check user authorization for token: %s", token), e);
}
} | 0 | Java | CWE-290 | Authentication Bypass by Spoofing | This attack-focused weakness is caused by improperly implemented authentication schemes that are subject to spoofing attacks. | https://cwe.mitre.org/data/definitions/290.html | vulnerable |
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("access denied (java.net.SocketPermission")
|| out.contains("access denied (\"java.net.SocketPermission\"")) {
messagedAccessDenied = true;
}
} | 0 | Java | CWE-862 | Missing Authorization | The software does not perform an authorization check when an actor attempts to access a resource or perform an action. | https://cwe.mitre.org/data/definitions/862.html | vulnerable |
protected XMLReader createXMLReader() throws SAXException {
return SAXHelper.createXMLReader(isValidating());
} | 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 Map<String, Object> getHelperUtilities() {
Map<String, Object> velocityContext = super.getHelperUtilities();
// Date tool
velocityContext.put("dateTool", new DateTool());
// Escape tool
velocityContext.put("escapeTool", new EscapeTool());
// Iterator tool
velocityContext.put("iteratorTool", new IteratorTool());
// List tool
velocityContext.put("listTool", new ListTool());
// Math tool
velocityContext.put("mathTool", new MathTool());
// Number tool
velocityContext.put("numberTool", new NumberTool());
// Portlet preferences
velocityContext.put(
"velocityPortletPreferences", new TemplatePortletPreferences());
// Sort tool
velocityContext.put("sortTool", new SortTool());
// Permissions
try {
velocityContext.put(
"rolePermission", RolePermissionUtil.getRolePermission());
}
catch (SecurityException se) {
_log.error(se, se);
}
return velocityContext;
} | 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 ensureCorrectTheme(Intent data) {
String oldListLayout = data.getStringExtra(SettingsActivity.SP_FEED_LIST_LAYOUT);
String newListLayout = mPrefs.getString(SettingsActivity.SP_FEED_LIST_LAYOUT,"0");
if (ThemeChooser.themeRequiresRestartOfUI() || !newListLayout.equals(oldListLayout)) {
NewsReaderListActivity.this.recreate();
} else if (data.hasExtra(SettingsActivity.CACHE_CLEARED)) {
resetUiAndStartSync();
}
} | 0 | Java | CWE-829 | Inclusion of Functionality from Untrusted Control Sphere | The software imports, requires, or includes executable functionality (such as a library) from a source that is outside of the intended control sphere. | https://cwe.mitre.org/data/definitions/829.html | vulnerable |
public byte[] engineGetIV()
{
if (engineSpec != null)
{
return engineSpec.getNonce();
}
return null;
} | 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 String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) {
acquireExclusiveLock();
try {
final String id = "OS" + System.currentTimeMillis() + random.nextLong();
sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword));
return id;
} finally {
releaseExclusiveLock();
}
}
| 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 long writeHtmlTo(long start, Writer w) throws IOException {
ConsoleAnnotationOutputStream caw = new ConsoleAnnotationOutputStream(
w, createAnnotator(Stapler.getCurrentRequest()), context, charset);
long r = super.writeLogTo(start,caw);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Cipher sym = PASSING_ANNOTATOR.encrypt();
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())));
return r;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
protected String getCorsDomain(String referer, String userAgent)
{
String dom = null;
if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".draw.io/") + 8);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".diagrams.net/") + 13);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".quipelements.com/") + 17);
}
// Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions)
// UA refers to old FF on macOS so low risk and fixes requests from existing servers
else if ((referer != null
&& referer.equals("draw.io Proxy Confluence Server"))
|| (userAgent != null && userAgent.equals(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0")))
{
dom = "";
}
return dom;
} | 0 | Java | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
public MultiMap set(CharSequence name, Iterable<CharSequence> values) {
HttpUtils.validateHeader(name, values);
headers.set(toLowerCase(name), values);
return this;
} | 1 | Java | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
public void existingDocumentNonTerminalFromUIDeprecatedCheckEscaping() 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 space=X.Y&tocreate=space
when(mockRequest.getParameter("space")).thenReturn("X.Y");
when(mockRequest.getParameter("tocreate")).thenReturn("space");
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note1: The space parameter was previously considered as space name, not space reference, so it is escaped.
// Note2: We are creating X\.Y.WebHome because the tocreate parameter says "space".
verify(mockURLFactory).createURL("X\\.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=X.Y", null,
"xwiki", context);
} | 0 | Java | CWE-862 | Missing Authorization | The software does not perform an authorization check when an actor attempts to access a resource or perform an action. | https://cwe.mitre.org/data/definitions/862.html | vulnerable |
public <T> List<T> search(String filter, Object[] filterArgs, Mapper<T> mapper, int maxResult) {
List<T> results = new ArrayList<>();
DirContext dirContext = getDirContext(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword());
try {
List<SearchResult> searchResults = search(dirContext, filter, filterArgs, maxResult, false);
for (SearchResult result : searchResults) {
results.add(mapper.mapObject(new ResultWrapper(result.getAttributes())));
}
} catch (NamingException e) {
throw new LdapException(e);
} finally {
closeContextSilently(dirContext);
}
return results;
} | 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 ChangeState(TimeTick when, String comment, Colors colors, String... states) {
if (states.length == 0) {
throw new IllegalArgumentException();
}
this.when = when;
this.states = states;
this.comment = comment;
this.colors = colors;
} | 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 engineInit(
int opmode,
Key key,
SecureRandom random)
throws InvalidKeyException
{
try
{
engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
}
catch (InvalidAlgorithmParameterException e)
{
throw new IllegalArgumentException("cannot handle supplied parameter spec: " + e.getMessage());
}
} | 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 setUp() throws Exception{
super.setUp();
sqlDataSetProvider.log = logger;
doAnswer(invocationOnMock -> {
String sql = (String) invocationOnMock.getArguments()[0];
System.out.println(sql);
return null;
}).when(logger).debug(anyString());
} | 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 testOfAsciiString() {
// Should produce a lower-cased AsciiString.
final AsciiString mixedCased = AsciiString.of("Foo");
assertThat((Object) HttpHeaderNames.of(mixedCased)).isNotSameAs(mixedCased);
assertThat(HttpHeaderNames.of(mixedCased).toString()).isEqualTo("foo");
// Should not produce a new instance for an AsciiString that's already lower-cased.
final AsciiString lowerCased = AsciiString.of("foo");
assertThat((Object) HttpHeaderNames.of(lowerCased)).isSameAs(lowerCased);
// Should reuse known header name instances.
assertThat((Object) HttpHeaderNames.of(AsciiString.of("date"))).isSameAs(HttpHeaderNames.DATE);
} | 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 EnvVars getCharacteristicEnvVars() {
EnvVars env = new EnvVars();
env.put("JENKINS_SERVER_COOKIE",Util.getDigestOf("ServerID:"+ Jenkins.getInstance().getSecretKey()));
env.put("HUDSON_SERVER_COOKIE",Util.getDigestOf("ServerID:"+ Jenkins.getInstance().getSecretKey())); // Legacy compatibility
env.put("JOB_NAME",getFullName());
return env;
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public void testEscapeSingleQuotesOnArgument()
{
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/bin" );
sh.setExecutable( "chmod" );
String[] args = { "arg'withquote" };
List shellCommandLine = sh.getShellCommandLine( args );
String cli = StringUtils.join( shellCommandLine.iterator(), " " );
System.out.println( cli );
assertEquals("cd /usr/bin && chmod 'arg'\\''withquote'", shellCommandLine.get(shellCommandLine.size() - 1));
} | 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 String getName()
{
return name;
} | 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 |
public PBEWithSHA1AESCBC256()
{
super(new CBCBlockCipher(new AESFastEngine()), PKCS12, SHA1, 256, 16);
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
public void qname() {
QName.get("element", "http://example.com/namespace");
QName.get("ns:element", "http://example.com/namespace");
} | 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 testWrapMemoryMapped() throws Exception {
File file = File.createTempFile("netty-test", "tmp");
FileChannel output = null;
FileChannel input = null;
ByteBuf b1 = null;
ByteBuf b2 = null;
try {
output = new RandomAccessFile(file, "rw").getChannel();
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
output.write(ByteBuffer.wrap(bytes));
input = new RandomAccessFile(file, "r").getChannel();
ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size());
b1 = buffer(m);
ByteBuffer dup = m.duplicate();
dup.position(2);
dup.limit(4);
b2 = buffer(dup);
Assert.assertEquals(b2, b1.slice(2, 2));
} finally {
if (b1 != null) {
b1.release();
}
if (b2 != null) {
b2.release();
}
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
file.delete();
}
} | 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 byte[] newIv() {
return newIv(DEFAULT_IV_LENGTH);
} | 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 |
public static synchronized InitialContext getInitialContext() throws NamingException {
if (context == null) {
try {
context = new InitialContext();
} catch (Exception e) {
throw handleException(e);
}
}
return 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 static CharSequence createOptimized(String value) {
HttpUtils.validateHeader(value);
return new AsciiString(value);
} | 1 | Java | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
public void setShouldOverWritePreviousValue() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.set("name", "value1");
headers.set("name", "value2");
assertThat(headers.size()).isEqualTo(1);
assertThat(headers.getAll("name").size()).isEqualTo(1);
assertThat(headers.getAll("name").get(0)).isEqualTo("value2");
assertThat(headers.get("name")).isEqualTo("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 IESwithDESede()
{
super(new IESEngine(new DHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
new PaddedBufferedBlockCipher(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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.