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 initWithcustomAccessRestrictor() throws ServletException {
prepareStandardInitialisation();
servlet.destroy();
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
public void testReadBytesAndWriteBytesWithFileChannel() throws IOException {
File file = PlatformDependent.createTempFile("file-channel", ".tmp", null);
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel();
// channelPosition should never be changed
long channelPosition = channel.position();
byte[] bytes = {'a', 'b', 'c', 'd'};
int len = bytes.length;
ByteBuf buffer = newBuffer(len);
buffer.resetReaderIndex();
buffer.resetWriterIndex();
buffer.writeBytes(bytes);
int oldReaderIndex = buffer.readerIndex();
assertEquals(len, buffer.readBytes(channel, 10, len));
assertEquals(oldReaderIndex + len, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(len, buffer2.writeBytes(channel, 10, len));
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex + len, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(0));
assertEquals('b', buffer2.getByte(1));
assertEquals('c', buffer2.getByte(2));
assertEquals('d', buffer2.getByte(3));
buffer.release();
buffer2.release();
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
file.delete();
}
} | 1 | Java | CWE-379 | Creation of Temporary File in Directory with Insecure Permissions | The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file. | https://cwe.mitre.org/data/definitions/379.html | safe |
public void testSquare_CarryBug_Reported()
{
ECFieldElement x = fe(new BigInteger("2fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd", 16));
BigInteger X = x.toBigInteger();
BigInteger R = X.multiply(X).mod(Q);
ECFieldElement z = x.square();
BigInteger Z = z.toBigInteger();
assertEquals(R, Z);
} | 1 | Java | CWE-19 | Data Processing Errors | Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information. | https://cwe.mitre.org/data/definitions/19.html | safe |
private void testModified()
throws Exception
{
KeyFactory kFact = KeyFactory.getInstance("DSA", "BC");
PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY);
Signature sig = Signature.getInstance("DSA", "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]));
}
catch (SignatureException e)
{
failed = true;
}
isTrue("sig verified when shouldn't", 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 |
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();
} | 0 | Java | NVD-CWE-noinfo | null | null | null | 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 |
protected String makeTokenSignature(long tokenExpiryTime, UserDetails userDetails) {
String expectedTokenSignature = MAC.mac(userDetails.getUsername() + ":" + tokenExpiryTime + ":"
+ "N/A" + ":" + getKey());
return expectedTokenSignature;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public SetupForm(final SetupPage parentPage)
{
super(parentPage, "setupform");
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 void beforeClass() throws IOException {
final Random r = new Random();
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) r.nextInt(255);
}
tmp = PlatformDependent.createTempFile("netty-traffic", ".tmp", null);
tmp.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tmp);
out.write(BYTES);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
} | 1 | Java | CWE-379 | Creation of Temporary File in Directory with Insecure Permissions | The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file. | https://cwe.mitre.org/data/definitions/379.html | safe |
public boolean loginValidate(String userName, String password, String email) {
String sql = "select * from voter_table where voter_name=? and password=? and email=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, password);
ps.setString(3, email);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return true;
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return false;
} | 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 |
void testEntryEquals() {
final HttpHeadersBase nameValue = newEmptyHeaders();
nameValue.add("name", "value");
final HttpHeadersBase nameValueCopy = newEmptyHeaders();
nameValueCopy.add("name", "value");
final Map.Entry<AsciiString, String> same1 = nameValue.iterator().next();
final Map.Entry<AsciiString, String> same2 = nameValueCopy.iterator().next();
assertThat(same2).isEqualTo(same1);
assertThat(same2.hashCode()).isEqualTo(same1.hashCode());
final HttpHeadersBase name1Value = newEmptyHeaders();
name1Value.add("name1", "value");
final HttpHeadersBase name2Value = newEmptyHeaders();
name2Value.add("name2", "value");
final Map.Entry<AsciiString, String> nameDifferent1 = name1Value.iterator().next();
final Map.Entry<AsciiString, String> nameDifferent2 = name2Value.iterator().next();
assertThat(nameDifferent1).isNotEqualTo(nameDifferent2);
assertThat(nameDifferent1.hashCode()).isNotEqualTo(nameDifferent2.hashCode());
final HttpHeadersBase nameValue1 = newEmptyHeaders();
nameValue1.add("name", "value1");
final HttpHeadersBase nameValue2 = newEmptyHeaders();
nameValue2.add("name", "value2");
final Map.Entry<AsciiString, String> valueDifferent1 = nameValue1.iterator().next();
final Map.Entry<AsciiString, String> valueDifferent2 = nameValue2.iterator().next();
assertThat(valueDifferent1).isNotEqualTo(valueDifferent2);
assertThat(valueDifferent1.hashCode()).isNotEqualTo(valueDifferent2.hashCode());
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public void setXMLFilter(XMLFilter filter) {
this.xmlFilter = filter;
} | 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 |
final void set(CharSequence name, Iterable<String> values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
} | 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 testKeySizeForUnknownCurve() {
try {
new ECKey.Builder(new ECKey.Curve("unknown"), ExampleKeyP256.X, ExampleKeyP256.Y).build().size();
fail();
} catch (UnsupportedOperationException e) {
assertEquals("Couldn't determine field size for curve unknown", e.getMessage());
}
} | 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 ECIESwithAESCBC()
{
super(new CBCBlockCipher(new AESFastEngine()), 16);
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
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());
}
}
}
} | 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 |
TEST(ProtocolSkipTest, SkipInt) {
IOBufQueue queue;
CompactProtocolWriter writer;
writer.setOutput(&queue);
writer.writeI32(123);
auto buf = queue.move();
CompactProtocolReader reader;
reader.setInput(buf.get());
reader.skip(TType::T_I32);
} | 1 | Java | CWE-755 | Improper Handling of Exceptional Conditions | The software does not handle or incorrectly handles an exceptional condition. | https://cwe.mitre.org/data/definitions/755.html | safe |
public PBEWithSHA1AESCBC192()
{
super(new CBCBlockCipher(new AESFastEngine()), PKCS12, SHA1, 192, 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 |
void iteratorSetShouldFail() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1", "value2", "value3");
headers.add("name2", "value4");
assertThat(headers.size()).isEqualTo(4);
assertThatThrownBy(() -> headers.iterator().next().setValue(""))
.isInstanceOf(UnsupportedOperationException.class);
} | 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 whenNameContainsMultipleValuesGetShouldReturnTheFirst() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1", "value2");
assertThat(headers.get("name1")).isEqualTo("value1");
} | 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 setUp() throws Exception {
MockitoAnnotations.initMocks(this);
} | 1 | Java | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | safe |
public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl windowControl, Translator trans) {
this.folderComponent = fc;
this.translator = trans;
this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath());
VelocityContainer main = new VelocityContainer("mc", VELOCITY_ROOT + "/movecopy.html", translator, this);
main.contextPut("fileselection", fileSelection);
//check if command is executed on a file list containing invalid filenames or paths
if(!fileSelection.getInvalidFileNames().isEmpty()) {
main.contextPut("invalidFileNames", fileSelection.getInvalidFileNames());
}
selTree = new MenuTree(null, "seltree", this);
FolderTreeModel ftm = new FolderTreeModel(ureq.getLocale(), fc.getRootContainer(),
true, false, true, fc.getRootContainer().canWrite() == VFSConstants.YES, new EditableFilter());
selTree.setTreeModel(ftm);
selectButton = LinkFactory.createButton(move ? "move" : "copy", main, this);
cancelButton = LinkFactory.createButton("cancel", main, this);
main.put("seltree", selTree);
if (move) {
main.contextPut("move", Boolean.TRUE);
}
setInitialComponent(main);
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 |
static private void close(Closeable file) {
if(file!=null) {
try {
file.close();
} catch (Exception ignore) {
}
}
} | 1 | Java | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null) {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject == null) {
Helpers.doForbidden(response);
return;
}
session = request.getSession(true);
session.setAttribute("subject", subject);
} else {
Subject subject = (Subject) session.getAttribute("subject");
if (subject == null) {
session.invalidate();
Helpers.doForbidden(response);
return;
}
}
String encoding = request.getHeader("Accept-Encoding");
boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
SessionTerminal st = (SessionTerminal) session.getAttribute("terminal");
if (st == null || st.isClosed()) {
st = new SessionTerminal(getCommandProcessor(), getThreadIO());
session.setAttribute("terminal", st);
}
String str = request.getParameter("k");
String f = request.getParameter("f");
String dump = st.handle(str, f != null && f.length() > 0);
if (dump != null) {
if (supportsGzip) {
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Type", "text/html");
try {
GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
gzos.write(dump.getBytes());
gzos.close();
} catch (IOException ie) {
LOG.info("Exception writing response: ", ie);
}
} else {
response.getOutputStream().write(dump.getBytes());
}
}
} | 0 | Java | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | vulnerable |
public boolean isPattern( final String path ) {
return path.indexOf( '*' ) != -1 || path.indexOf( '?' ) != -1;
} | 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 |
protected final void populateUrlAttributeMap(final Map<String, String> urlParameters) {
urlParameters.put("pgtUrl", this.proxyCallbackUrl);
} | 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 doubleDotsInPath() {
BAD_DOUBLE_DOT_PATTERNS.forEach(pattern -> assertProhibited(pattern));
GOOD_DOUBLE_DOT_PATTERNS.forEach(pattern -> {
final String path = pattern.startsWith("/") ? pattern : '/' + pattern;
final PathAndQuery res = parse(path);
assertThat(res).as("Ensure %s is allowed.", path).isNotNull();
assertThat(res.path()).as("Ensure %s is parsed as-is.", path).isEqualTo(path);
});
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
private void checkMimeType(String given, String expected) throws IOException, URISyntaxException {
HttpExchange exchange = prepareExchange("http://localhost:8080/jolokia/read/java.lang:type=Memory/HeapMemoryUsage?mimeType=" + given);
// Simple GET method
expect(exchange.getRequestMethod()).andReturn("GET");
Headers header = new Headers();
ByteArrayOutputStream out = prepareResponse(handler, exchange, header);
handler.doHandle(exchange);
assertEquals(header.getFirst("content-type"),expected + "; charset=utf-8");
} | 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 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());
} | 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 testArraySafeBitLength_IntegerOverflow() {
try {
ByteUtils.safeBitLength(new byte[Integer.MAX_VALUE]);
fail();
} catch (OutOfMemoryError e) {
System.out.println("Test not run due to " + e);
} catch (IntegerOverflowException e) {
assertEquals("Integer overflow", e.getMessage());
}
} | 1 | Java | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
private SecretKey getKey() {
try {
if (secret==null) {
synchronized (this) {
if (secret==null) {
byte[] payload = load();
if (payload==null) {
payload = ConfidentialStore.get().randomBytes(256);
store(payload);
}
// Due to the stupid US export restriction JDK only ships 128bit version.
secret = new SecretKeySpec(payload,0,128/8, KEY_ALGORITHM);
}
}
}
return secret;
} catch (IOException e) {
throw new Error("Failed to load the key: "+getId(),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 |
public void addViolation(String message, Map<String, Object> messageParameters) {
violationOccurred = true;
getContextWithMessageParameters(messageParameters)
.buildConstraintViolationWithTemplate(sanitizeTemplate(message))
.addConstraintViolation();
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public BigInteger[] generateSignature(
byte[] message)
{
DSAParameters params = key.getParameters();
BigInteger q = params.getQ();
BigInteger m = calculateE(q, message);
BigInteger x = ((DSAPrivateKeyParameters)key).getX();
if (kCalculator.isDeterministic())
{
kCalculator.init(q, x, message);
}
else
{
kCalculator.init(q, random);
}
BigInteger k = kCalculator.nextK();
BigInteger r = params.getG().modPow(k, params.getP()).mod(q);
k = k.modInverse(q).multiply(m.add(x.multiply(r)));
BigInteger s = k.mod(q);
return new BigInteger[]{ r, s };
} | 0 | Java | CWE-361 | 7PK - Time and State | This category represents one of the phyla in the Seven Pernicious Kingdoms vulnerability classification. It includes weaknesses related to the improper management of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. According to the authors of the Seven Pernicious Kingdoms, "Distributed computation is about time and state. That is, in order for more than one component to communicate, state must be shared, and all that takes time. Most programmers anthropomorphize their work. They think about one thread of control carrying out the entire program in the same way they would if they had to do the job themselves. Modern computers, however, switch between tasks very quickly, and in multi-core, multi-CPU, or distributed systems, two events may take place at exactly the same time. Defects rush to fill the gap between the programmer's model of how a program executes and what happens in reality. These defects are related to unexpected interactions between threads, processes, time, and information. These interactions happen through shared state: semaphores, variables, the file system, and, basically, anything that can store information." | https://cwe.mitre.org/data/definitions/361.html | vulnerable |
public void testScanOnBoot() throws Exception {
WebClient wc = createWebClient();
// scan on boot should have run the scan
assertTrue(monitor.getLogFile().exists());
assertTrue("scan on boot should have turned this off",!monitor.isScanOnBoot());
// and data should be migrated
verifyRewrite(jenkins.getRootDir());
// should be no warning/error now
HtmlPage manage = wc.goTo("/manage");
assertEquals(0,manage.selectNodes("//*[class='error']").size());
assertEquals(0,manage.selectNodes("//*[class='warning']").size());
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public XMLReader getXMLReader() throws SAXException {
if (xmlReader == null) {
xmlReader = createXMLReader();
}
return xmlReader;
} | 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 static SecretKey decryptCEK(final PrivateKey priv,
final byte[] encryptedCEK,
final int keyLength,
final Provider provider)
throws JOSEException {
try {
Cipher cipher = CipherHelper.getInstance("RSA/ECB/PKCS1Padding", provider);
cipher.init(Cipher.DECRYPT_MODE, priv);
byte[] secretKeyBytes = cipher.doFinal(encryptedCEK);
if (ByteUtils.safeBitLength(secretKeyBytes) != keyLength) {
// CEK key length mismatch
return null;
}
return new SecretKeySpec(secretKeyBytes, "AES");
} catch (Exception e) {
// java.security.NoSuchAlgorithmException
// java.security.InvalidKeyException
// javax.crypto.IllegalBlockSizeException
// javax.crypto.BadPaddingException
throw new JOSEException("Couldn't decrypt Content Encryption Key (CEK): " + e.getMessage(), e);
}
} | 1 | Java | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
private String getOriginOrReferer(HttpServletRequest pReq) {
String origin = pReq.getHeader("Origin");
if (origin == null) {
origin = pReq.getHeader("Referer");
}
return origin != null ? origin.replaceAll("[\\n\\r]*","") : null;
} | 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 |
ReservedChar(int rawChar, String percentEncodedChar, byte marker) {
this.rawChar = rawChar;
this.percentEncodedChar = percentEncodedChar;
this.marker = marker;
} | 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 testInvalidGroupIds() {
testInvalidGroupId("John<b>Doe</b>",true);
testInvalidGroupId("Jane'Doe'",true);
testInvalidGroupId("John&Doe",true);
testInvalidGroupId("Jane\"\"Doe",true);
} | 1 | Java | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
public 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 |
public IESwithDESedeCBC()
{
super(new IESEngine(new DHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()))), 8);
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
private void testKeyFactory(ECPublicKey pub, ECPrivateKey priv)
throws Exception
{
KeyFactory ecFact = KeyFactory.getInstance("ECDSA");
ECPublicKeySpec pubSpec = (ECPublicKeySpec)ecFact.getKeySpec(pub, ECPublicKeySpec.class);
ECPrivateKeySpec privSpec = (ECPrivateKeySpec)ecFact.getKeySpec(priv, ECPrivateKeySpec.class);
if (!pubSpec.getW().equals(pub.getW()) || !pubSpec.getParams().getCurve().equals(pub.getParams().getCurve()))
{
fail("pubSpec not correct");
}
if (!privSpec.getS().equals(priv.getS()) || !privSpec.getParams().getCurve().equals(priv.getParams().getCurve()))
{
fail("privSpec not correct");
}
ECPublicKey pubKey = (ECPublicKey)ecFact.translateKey(pub);
ECPrivateKey privKey = (ECPrivateKey)ecFact.translateKey(priv);
if (!pubKey.getW().equals(pub.getW()) || !pubKey.getParams().getCurve().equals(pub.getParams().getCurve()))
{
fail("pubKey not correct");
}
if (!privKey.getS().equals(priv.getS()) || !privKey.getParams().getCurve().equals(priv.getParams().getCurve()))
{
fail("privKey not correct");
}
} | 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 testInvalidUserId(final String userId, final boolean mustFail) {
adminPage();
findElementByLink("Configure Users, Groups and On-Call Roles").click();
findElementByLink("Configure Users").click();
findElementByLink("Add new user").click();
enterText(By.id("userID"), userId);
enterText(By.id("pass1"), "SmokeTestPassword");
enterText(By.id("pass2"), "SmokeTestPassword");
findElementByXpath("//button[@type='submit' and text()='OK']").click();
if (mustFail) {
try {
final Alert alert = wait.withTimeout(Duration.of(5, ChronoUnit.SECONDS)).until(ExpectedConditions.alertIsPresent());
alert.dismiss();
} catch (final Exception e) {
LOG.debug("Got an exception waiting for a 'invalid user ID' alert.", e);
throw e;
}
} else {
wait.until(ExpectedConditions.elementToBeClickable(By.name("finish")));
}
} | 1 | Java | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
protected Key engineDoPhase(
Key key,
boolean lastPhase)
throws InvalidKeyException, IllegalStateException
{
if (x == null)
{
throw new IllegalStateException("Diffie-Hellman not initialised.");
}
if (!(key instanceof DHPublicKey))
{
throw new InvalidKeyException("DHKeyAgreement doPhase requires DHPublicKey");
}
DHPublicKey pubKey = (DHPublicKey)key;
if (!pubKey.getParams().getG().equals(g) || !pubKey.getParams().getP().equals(p))
{
throw new InvalidKeyException("DHPublicKey not for this KeyAgreement!");
}
if (lastPhase)
{
result = ((DHPublicKey)key).getY().modPow(x, p);
return null;
}
else
{
result = ((DHPublicKey)key).getY().modPow(x, p);
}
return new BCDHPublicKey(result, pubKey.getParams());
} | 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 |
private boolean isFileWithinDirectory(
final File dir,
final File file
) throws IOException {
final File dir_ = dir.getAbsoluteFile();
if (dir_.isDirectory()) {
final File fl = new File(dir_, file.getPath());
if (fl.isFile()) {
if (fl.getCanonicalPath().startsWith(dir_.getCanonicalPath())) {
// Prevent accessing files outside the load-path.
// E.g.: ../../coffee
return true;
}
}
}
return false;
} | 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 testGetShellCommandLineNonWindows()
throws Exception
{
Commandline cmd = new Commandline( new BourneShell() );
cmd.setExecutable( "/usr/bin" );
cmd.addArguments( new String[] {
"a",
"b"
} );
String[] shellCommandline = cmd.getShellCommandline();
assertEquals( "Command line size", 3, shellCommandline.length );
assertEquals( "/bin/sh", shellCommandline[0] );
assertEquals( "-c", shellCommandline[1] );
if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
{
assertEquals( "\\usr\\bin a b", shellCommandline[2] );
}
else
{
assertEquals( "'/usr/bin' 'a' 'b'", shellCommandline[2] );
}
} | 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 void testGeneration()
throws Exception
{
//
// ECDSA generation test
//
byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
Signature s = Signature.getInstance("ECDSA", "BC");
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
EllipticCurve curve = new EllipticCurve(
new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECParameterSpec ecSpec = new ECParameterSpec(
curve,
ECPointUtil.decodePoint(curve, Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n
1); // h
g.initialize(ecSpec, new SecureRandom());
KeyPair p = g.generateKeyPair();
PrivateKey sKey = p.getPrivate();
PublicKey vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("ECDSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("ECDSA verification failed");
}
testKeyFactory((ECPublicKey)vKey, (ECPrivateKey)sKey);
testSerialise((ECPublicKey)vKey, (ECPrivateKey)sKey);
} | 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 void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,
String parent) throws XWikiException
{
XWiki xwiki = context.getWiki();
DocumentReferenceResolver<String> resolver = getCurrentMixedDocumentReferenceResolver();
// Set the locale and default locale, considering that we're creating the original version of the document
// (not a translation).
newDocument.setLocale(Locale.ROOT);
if (newDocument.getDefaultLocale() == Locale.ROOT) {
newDocument.setDefaultLocale(xwiki.getLocalePreference(context));
}
// Copy the template.
DocumentReference templateReference = resolver.resolve(template);
newDocument.readFromTemplate(templateReference, context);
// Set the parent field.
if (!StringUtils.isEmpty(parent)) {
DocumentReference parentReference = resolver.resolve(parent);
newDocument.setParentReference(parentReference);
}
// Set the document title
if (title != null) {
newDocument.setTitle(title);
}
// Set the author and creator.
DocumentReference currentUserReference = context.getUserReference();
newDocument.setAuthorReference(currentUserReference);
newDocument.setCreatorReference(currentUserReference);
// Make sure the user is allowed to make this modification
xwiki.checkSavingDocument(currentUserReference, newDocument, context);
xwiki.saveDocument(newDocument, 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 |
/*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) {
try {
String plainText = new String(cipher.doFinal(in), UTF_8);
if(plainText.endsWith(MAGIC))
return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));
return null;
} catch (GeneralSecurityException e) {
return null; // if the key doesn't match with the bytes, it can result in BadPaddingException
}
} | 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 |
TEST(ProtocolSkipTest, SkipStopInContainer) {
IOBufQueue queue;
CompactProtocolWriter writer;
writer.setOutput(&queue);
writer.writeListBegin(TType::T_STOP, 1u << 30);
auto buf = queue.move();
CompactProtocolReader reader;
reader.setInput(buf.get());
bool thrown = false;
try {
reader.skip(TType::T_LIST);
} catch (const TProtocolException& ex) {
EXPECT_EQ(TProtocolException::INVALID_DATA, ex.getType());
thrown = true;
}
EXPECT_TRUE(thrown);
} | 1 | Java | CWE-755 | Improper Handling of Exceptional Conditions | The software does not handle or incorrectly handles an exceptional condition. | https://cwe.mitre.org/data/definitions/755.html | safe |
public String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
return this.displayCategory(friendlyUrl,ref,model,request,response,locale);
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
public SAXReader(XMLReader xmlReader) {
this.xmlReader = xmlReader;
} | 0 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | vulnerable |
private String getMimeType(ParsedUri pParsedUri) {
return MimeTypeUtil.getResponseMimeType(
pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue()),
configuration.get(ConfigKey.MIME_TYPE),
pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()));
} | 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 UChange changeBack(UGraphic ug) {
final HColor color = ug.getParam().getColor();
if (color == null) {
return new HColorNone().bg();
}
return color.bg();
} | 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 InputStream getResourceAsStream(String path) throws IOException {
final URL rootResourceURL = classLoader.getResource(resourceRoot);
if (rootResourceURL == null) {
return null;
}
final String rootPath = rootResourceURL.getPath();
final URL resourceURL = classLoader.getResource(resourceRoot + path);
if(resourceURL == null || !resourceURL.getPath().startsWith(rootPath)) {
return null;
}
else {
return resourceURL.openConnection().getInputStream();
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String oldName = request.getParameter("groupName");
String newName = request.getParameter("newName");
if (newName != null && newName.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group ID must not contain any HTML markup.");
}
if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
m_groupRepository.renameGroup(oldName, newName);
}
return listGroups(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 |
void testClearResetsPseudoHeaderDivision() {
final HttpHeadersBase http2Headers = newHttp2Headers();
http2Headers.method(HttpMethod.POST);
http2Headers.set("some", "value");
http2Headers.clear();
http2Headers.method(HttpMethod.GET);
assertThat(http2Headers.names()).containsExactly(HttpHeaderNames.METHOD);
assertThat(http2Headers.getAll(HttpHeaderNames.METHOD)).containsExactly("GET");
} | 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 String resolveDriverClassName(DriverClassNameResolveRequest request) {
return driverResources.resolveSqlDriverNameFromJar(request.getJdbcDriverFileUrl());
} | 0 | Java | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String oldName = request.getParameter("groupName");
String newName = request.getParameter("newName");
if (newName != null && newName.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group ID must not contain any HTML markup.");
}
if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
m_groupRepository.renameGroup(oldName, newName);
}
return listGroups(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 |
private Runnable getStandardRequestSetup() {
return new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(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 String getXmlFactoryFactory() {
return PGProperty.XML_FACTORY_FACTORY.get(properties);
} | 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 boolean add(MediaPackage sourceMediaPackage, AccessControlList acl, Date now) throws SolrServerException,
UnauthorizedException {
try {
SolrInputDocument episodeDocument = createEpisodeInputDocument(sourceMediaPackage, acl);
Schema.setOcModified(episodeDocument, now);
SolrInputDocument seriesDocument = createSeriesInputDocument(sourceMediaPackage.getSeries(), acl);
if (seriesDocument != null)
Schema.enrich(episodeDocument, seriesDocument);
// If neither an episode nor a series was contained, there is no point in trying to update
if (episodeDocument == null && seriesDocument == null) {
logger.warn("Neither episode nor series metadata found");
return false;
}
// Post everything to the search index
if (episodeDocument != null)
solrServer.add(episodeDocument);
if (seriesDocument != null)
solrServer.add(seriesDocument);
solrServer.commit();
return true;
} catch (Exception e) {
logger.error("Unable to add mediapackage {} to index", sourceMediaPackage.getIdentifier());
throw new SolrServerException(e);
}
} | 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 static SAXReader getSafeSaxReader() throws Exception
{
SAXReader xmlReader = new SAXReader();
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
return xmlReader;
} | 1 | Java | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
private void visitorPermission(Invocation ai) {
ai.invoke();
String templateName = ai.getReturnValue();
if (templateName == null) {
return;
}
GlobalResourceHandler.printUserTime("Template before");
String templatePath = TemplateHelper.fullTemplateInfo(ai.getController(), true);
GlobalResourceHandler.printUserTime("Template after");
TemplateVO templateVO = new TemplateService().getTemplateVO(JFinal.me().getContextPath(), new File(PathKit.getWebRootPath() + templatePath));
String ext = ZrLogUtil.getViewExt(templateVO.getViewType());
if (ai.getController().getAttr("log") != null) {
ai.getController().setAttr("pageLevel", 1);
} else if (ai.getController().getAttr("data") != null) {
if ("/".equals(ai.getActionKey()) && new File(PathKit.getWebRootPath() + templatePath + "/" + templateName + ext).exists()) {
ai.getController().setAttr("pageLevel", 2);
} else {
templateName = "page";
ai.getController().setAttr("pageLevel", 1);
}
} else {
ai.getController().setAttr("pageLevel", 2);
}
fullDevData(ai.getController());
ai.getController().render(templatePath + "/" + templateName + ext);
} | 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 requestResetPasswordWithoutPR() throws Exception
{
when(this.authorizationManager.hasAccess(Right.PROGRAM)).thenReturn(false);
assertNull(this.scriptService.requestResetPassword(mock(UserReference.class)));
verify(this.resetPasswordManager, never()).requestResetPassword(any());
verify(this.resetPasswordManager, never()).sendResetPasswordEmailRequest(any());
} | 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 existingDocumentFromUITemplateProviderSpecifiedButOldSpaceType() 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&templateProvider=XWiki.MyTemplateProvider
String templateProviderFullName = "XWiki.MyTemplateProvider";
when(mockRequest.getParameter("spaceReference")).thenReturn("X");
when(mockRequest.getParameter("name")).thenReturn("Y");
when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);
// Mock 1 existing template provider
mockExistingTemplateProviders(templateProviderFullName,
new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, null,
"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);
// Note: We are creating X.Y.WebHome as non-terminal, since the template provider does not specify a "terminal"
// property and we fallback on the "type" property's value. Also using the template extracted from the template
// provider.
verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
"template=XWiki.MyTemplate&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 void clientIdChanged(ClientModel client, String newClientId) {
logger.debugf("Updating clientId from '%s' to '%s'", client.getClientId(), newClientId);
UserModel serviceAccountUser = realmManager.getSession().users().getServiceAccount(client);
if (serviceAccountUser != null) {
String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + newClientId;
serviceAccountUser.setUsername(username);
serviceAccountUser.setEmail(username + "@placeholder.org");
}
} | 0 | Java | CWE-798 | Use of Hard-coded Credentials | The software contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data. | https://cwe.mitre.org/data/definitions/798.html | vulnerable |
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (!haskey) {
// The key is not set yet - return the plaintext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
return length;
}
if (space < 16 || length > (space - 16))
throw new ShortBufferException();
setup(ad);
encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
poly.update(ciphertext, ciphertextOffset, length);
finish(ad, length);
System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16);
return length + 16;
} | 0 | Java | CWE-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 |
protected ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException {
int type = read();
if (type < 0) {
throw new EOFException();
}
switch (type) {
case ThrowableObjectOutputStream.TYPE_EXCEPTION:
return ObjectStreamClass.lookup(Exception.class);
case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:
return ObjectStreamClass.lookup(StackTraceElement.class);
case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:
return verify(super.readClassDescriptor());
case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:
String className = readUTF();
Class<?> clazz = loadClass(className);
return verify(ObjectStreamClass.lookup(clazz));
default:
throw new StreamCorruptedException(
"Unexpected class descriptor type: " + type);
}
} | 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 static SecretKey decryptCEK(final SecretKey kek,
final byte[] iv,
final AuthenticatedCipherText authEncrCEK,
final int keyLength,
final Provider provider)
throws JOSEException {
byte[] keyBytes = AESGCM.decrypt(kek, iv, authEncrCEK.getCipherText(), new byte[0], authEncrCEK.getAuthenticationTag(), provider);
if (ByteUtils.safeBitLength(keyBytes) != keyLength) {
throw new KeyLengthException("CEK key length mismatch: " + ByteUtils.safeBitLength(keyBytes) + " != " + keyLength);
}
return new SecretKeySpec(keyBytes, "AES");
} | 1 | Java | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
public static byte[] decryptAuthenticated(final SecretKey secretKey,
final byte[] iv,
final byte[] cipherText,
final byte[] aad,
final byte[] authTag,
final Provider ceProvider,
final Provider macProvider)
throws JOSEException {
// Extract MAC + AES/CBC keys from input secret key
CompositeKey compositeKey = new CompositeKey(secretKey);
// AAD length to 8 byte array
byte[] al = AAD.computeLength(aad);
// Check MAC
int hmacInputLength = aad.length + iv.length + cipherText.length + al.length;
byte[] hmacInput = ByteBuffer.allocate(hmacInputLength).
put(aad).
put(iv).
put(cipherText).
put(al).
array();
byte[] hmac = HMAC.compute(compositeKey.getMACKey(), hmacInput, macProvider);
byte[] expectedAuthTag = Arrays.copyOf(hmac, compositeKey.getTruncatedMACByteLength());
boolean macCheckPassed = true;
if (! ConstantTimeUtils.areEqual(expectedAuthTag, authTag)) {
// Thwart timing attacks by delaying exception until after decryption
macCheckPassed = false;
}
byte[] plainText = decrypt(compositeKey.getAESKey(), iv, cipherText, ceProvider);
if (! macCheckPassed) {
throw new JOSEException("MAC check failed");
}
return plainText;
} | 0 | Java | CWE-354 | Improper Validation of Integrity Check Value | The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission. | https://cwe.mitre.org/data/definitions/354.html | vulnerable |
private static boolean doesNotContainFileColon(String path) {
return !path.contains("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 |
private static void assertQueryStringAllowed(String rawPath) {
assertThat(rawPath).startsWith("/?");
final String expectedQuery = rawPath.substring(2);
assertQueryStringAllowed(rawPath, expectedQuery);
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
final void set(CharSequence name, String... values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public 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();
}
}
| 0 | Java | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
public void privateMsgInMuc(Conversation conversation, String nick) {
switchToConversation(conversation, null, false, nick, true, false);
} | 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 translate(EmoteListPacket packet, GeyserSession session) {
if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
return;
}
session.refreshEmotes(packet.getPieceIds());
} | 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 CCM()
{
super(new CCMBlockCipher(new AESEngine()), false, 16);
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
public Document read(URL url) throws DocumentException {
String systemID = url.toExternalForm();
InputSource source = new InputSource(systemID);
if (this.encoding != null) {
source.setEncoding(this.encoding);
}
return read(source);
} | 0 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | vulnerable |
public CryptoConfidentialKey(Class owner, String shortName) {
this(owner.getName()+'.'+shortName);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public SymbolContext getContext(ISkinParam skinParam, Style style) {
return new SymbolContext(getBackColor(skinParam, style), getLineColor(skinParam, style))
.withStroke(new UStroke(1.5));
} | 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 testUri() {
final HttpHeadersBase headers = newHttp2Headers();
assertThat(headers.uri()).isEqualTo(URI.create("https://netty.io/index.html"));
} | 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 Response processControlCommand(ControlCommand command) throws Exception {
String control = command.getCommand();
if (control != null && control.equals("shutdown")) {
System.exit(0);
}
return null;
} | 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 Mapper retrieveMapperById(String mapperId) {
List<PersistedMapper> mappers = dbInstance.getCurrentEntityManager()
.createNamedQuery("loadMapperByKey", PersistedMapper.class)
.setParameter("mapperId", mapperId)
.getResultList();
PersistedMapper pm = mappers.isEmpty() ? null : mappers.get(0);
if(pm != null && StringHelper.containsNonWhitespace(pm.getXmlConfiguration())) {
String configuration = pm.getXmlConfiguration();
Object obj = XStreamHelper.createXStreamInstance().fromXML(configuration);
if(obj instanceof Mapper) {
return (Mapper)obj;
}
}
return null;
} | 0 | Java | CWE-91 | XML Injection (aka Blind XPath Injection) | The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system. | https://cwe.mitre.org/data/definitions/91.html | vulnerable |
} catch (Exception e) {
throw new RuntimeException(e);
} | 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 SAXEntityResolver(String uriPrefix) {
this.uriPrefix = uriPrefix;
} | 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 doesNotAllowWhitespaceInSort() {
Sort sort = new Sort("case when foo then bar");
applySorting("select p from Person p", sort, "p");
} | 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 <T> List<T> search(final String filter, final Object[] filterArgs, final Mapper<T> mapper, final int maxResultCount) {
final List<T> searchResults = new ArrayList<>();
for (String searchBase : ldapConfiguration.getSearchBases()) {
int resultsToFetch = resultsToFetch(maxResultCount, searchResults.size());
if (resultsToFetch == -1) {
break;
}
try {
final SearchRequest searchRequest = new SearchRequestImpl()
.setScope(SearchScope.SUBTREE)
.addAttributes("*")
.setSizeLimit(resultsToFetch)
.setFilter(format(filter, filterArgs))
.setTimeLimit(ldapConfiguration.getSearchTimeout())
.setBase(new Dn(searchBase));
searchResults.addAll(ldapConnectionTemplate.search(searchRequest, mapper));
} catch (LdapException e) {
LOG.error(e.getMessage(), e);
}
}
return searchResults;
} | 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 |
setImmediate(() => {
if (!this.pendingPublishRequestCount) {
return;
}
const starving_subscription = this._find_starving_subscription();
if (starving_subscription) {
doDebug && debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId = "), starving_subscription.id);
starving_subscription.process_subscription();
}
}); | 0 | Java | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
private ECFieldElement generateMultiplyInputA_OpenSSLBug()
{
int[] x = Nat256.create();
x[0] = RANDOM.nextInt() >>> 1;
x[4] = 3;
x[7] = -1;
return fe(Nat256.toBigInteger(x));
} | 1 | Java | CWE-19 | Data Processing Errors | Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information. | https://cwe.mitre.org/data/definitions/19.html | safe |
public OldIESwithAES()
{
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 int addFileName(String file) {
workUnitList.add(new WorkUnit(file));
return size();
} | 0 | Java | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
private HColor getColorLegacy(ISkinParam skinParam, ColorParam colorParam, Stereotype stereo) {
return new 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 PACLVelocityTemplate(
String templateId, String templateContent, String errorTemplateId,
String errorTemplateContent, VelocityContext velocityContext,
VelocityEngine velocityEngine,
TemplateContextHelper templateContextHelper, PACLPolicy paclPolicy) {
super(
templateId, templateContent, errorTemplateId, errorTemplateContent,
velocityContext, velocityEngine, templateContextHelper);
_paclPolicy = paclPolicy;
} | 1 | Java | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
public void handle(HttpServletRequest request, 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();
Element body = env.element("body");
// First handle any new subscriptions
List<SubscriptionRequest> requests = new ArrayList<SubscriptionRequest>();
List<Element> elements = body.elements("subscribe");
for (Element e : elements)
{
requests.add(new SubscriptionRequest(e.attributeValue("topic")));
}
ServletLifecycle.beginRequest(request);
try
{
ServletContexts.instance().setRequest(request);
Manager.instance().initializeTemporaryConversation();
ServletLifecycle.resumeConversation(request);
for (SubscriptionRequest req : requests)
{
req.subscribe();
}
// Then handle any unsubscriptions
List<String> unsubscribeTokens = new ArrayList<String>();
elements = body.elements("unsubscribe");
for (Element e : elements)
{
unsubscribeTokens.add(e.attributeValue("token"));
}
for (String token : unsubscribeTokens)
{
RemoteSubscriber subscriber = SubscriptionRegistry.instance().
getSubscription(token);
if (subscriber != null)
{
subscriber.unsubscribe();
}
}
}
finally
{
Lifecycle.endRequest();
}
// Package up the response
marshalResponse(requests, response.getOutputStream());
} | 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 |
private int _readAndWriteBytes(OutputStream out, int total) throws IOException
{
int left = total;
while (left > 0) {
int avail = _inputEnd - _inputPtr;
if (_inputPtr >= _inputEnd) {
loadMoreGuaranteed();
avail = _inputEnd - _inputPtr;
}
int count = Math.min(avail, left);
out.write(_inputBuffer, _inputPtr, count);
_inputPtr += count;
left -= count;
}
_tokenIncomplete = false;
return total;
} | 0 | Java | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
public void newDocumentWebHomeFromURLTemplateProviderSpecifiedTerminalOverriddenFromUIToNonTerminal()
throws Exception
{
// new document = xwiki:X.Y.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X", "Y"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(true);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider
String templateProviderFullName = "XWiki.MyTemplateProvider";
when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);
when(mockRequest.getParameter("tocreate")).thenReturn("nonterminal");
// Mock 1 existing template provider
mockExistingTemplateProviders(templateProviderFullName,
new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, true);
// 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 the document X.Y.WebHome as non-terminal even if the template provider says otherwise.
// Also using a template, as specified in the template provider.
verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
"template=XWiki.MyTemplate&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 String readStringBody(int size) throws TException {
ensureContainerHasEnough(size, TType.BYTE);
checkReadLength(size);
byte[] buf = new byte[size];
trans_.readAll(buf, 0, size);
return new String(buf, StandardCharsets.UTF_8);
} | 1 | Java | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
public void testInvalidGroupId(final String groupId, final boolean mustFail) {
adminPage();
findElementByLink("Configure Users, Groups and On-Call Roles").click();
findElementByLink("Configure Groups").click();
findElementByLink("Add new group").click();
enterText(By.id("groupName"), groupId);
enterText(By.id("groupComment"), "SmokeTestComment");
findElementByXpath("//button[@type='submit' and text()='OK']").click();
if (mustFail) {
try {
final Alert alert = wait.withTimeout(Duration.of(5, ChronoUnit.SECONDS)).until(ExpectedConditions.alertIsPresent());
alert.dismiss();
} catch (final Exception e) {
LOG.debug("Got an exception waiting for a 'invalid group ID' alert.", e);
throw e;
}
} else {
wait.until(ExpectedConditions.elementToBeClickable(By.name("finish")));
}
} | 1 | Java | CWE-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 |
protected synchronized void releaseNativeResources() {
clear();
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.