code
stringlengths 12
2.05k
| label
int64 0
1
| programming_language
stringclasses 9
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
103
⌀ | description
stringlengths 36
1.23k
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
public static <T> T throw0(Throwable throwable) {
if (throwable == null) throw new NullPointerException();
getUnsafe().throwException(throwable);
throw new RuntimeException();
} | 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 |
void rawUnicode() {
// 2- and 3-byte UTF-8
final PathAndQuery res1 = PathAndQuery.parse("/\u00A2?\u20AC"); // ¢ and €
assertThat(res1).isNotNull();
assertThat(res1.path()).isEqualTo("/%C2%A2");
assertThat(res1.query()).isEqualTo("%E2%82%AC");
// 4-byte UTF-8
final PathAndQuery res2 = PathAndQuery.parse("/\uD800\uDF48"); // 𐍈
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/%F0%90%8D%88");
assertThat(res2.query()).isNull();
// 5- and 6-byte forms are only theoretically possible, so we won't test them here.
} | 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 addElementQualifiedPrefix() {
Element root = DocumentHelper.createElement("root");
root.addElement("ns:element>name", "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 |
private boolean exractAndLoad(ArrayList<String> errors, String version, String customPath, String resourcePath) {
URL resource = classLoader.getResource(resourcePath);
if( resource !=null ) {
String libName = name + "-" + getBitModel();
if( version !=null) {
libName += "-" + version;
}
if( customPath!=null ) {
// Try to extract it to the custom path...
File target = file(customPath, map(libName));
if( extract(errors, resource, target) ) {
if( load(errors, target) ) {
return true;
}
}
}
// Fall back to extracting to the tmp dir
customPath = System.getProperty("java.io.tmpdir");
File target = file(customPath, map(libName));
if( extract(errors, resource, target) ) {
if( load(errors, target) ) {
return true;
}
}
}
return false;
} | 0 | 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 | vulnerable |
private final void servlet31(HttpServletRequest request) {
try {
for(Part part:request.getParts()) {
if(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith("text/plain"))) {
contentType = part.getContentType();
filename = part.getSubmittedFileName();
if(filename != null) {
filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
} else {
filename = "upload-" + UUID.randomUUID().toString().replace("-", "");
}
file = new File(WebappHelper.getTmpDir(), filename);
part.write(file.getAbsolutePath());
file = new File(WebappHelper.getTmpDir(), filename);
} else {
String value = IOUtils.toString(part.getInputStream(), request.getCharacterEncoding());
fields.put(part.getName(), value);
}
try {
part.delete();
} catch (Exception e) {
//we try (tomcat doesn't send exception but undertow)
}
}
} catch (IOException | ServletException e) {
log.error("", e);
}
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
public void testImportZipSigAndEmptyConsumerZip()
throws Exception {
PKIUtility pki = mock(PKIUtility.class);
Importer i = new Importer(null, null, null, null, null, null, null,
pki, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
// Mock a passed signature check:
when(pki.verifySHA256WithRSAHashWithUpstreamCACert(any(InputStream.class),
any(byte [].class))).thenReturn(true);
File archive = new File("/tmp/file.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive));
out.putNextEntry(new ZipEntry("signature"));
out.write("This is the placeholder for the signature file".getBytes());
File ceArchive = new File("/tmp/consumer_export.zip");
ZipOutputStream cezip = new ZipOutputStream(new FileOutputStream(ceArchive));
cezip.putNextEntry(new ZipEntry("This is just a zip file with no content"));
cezip.close();
addFileToArchive(out, ceArchive);
out.close();
try {
i.loadExport(owner, archive, co);
}
catch (ImportExtractionException e) {
assertTrue(e.getMessage().contains("consumer_export archive has no contents"));
return;
}
fail();
} | 1 | Java | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
private static void handleResponse(HttpURLConnection conn, int statusCode, String terminalWidth) {
try {
// 200 - modules found
// Other - Error occurred, json returned with the error message
MapValue payload;
if (statusCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()))) {
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
payload = (MapValue) JSONParser.parse(result.toString());
} catch (IOException e) {
throw ErrorUtil.createCommandException(e.getMessage());
}
if (payload.getIntValue("count") > 0) {
ArrayValue modules = payload.getArrayValue("modules");
printModules(modules, terminalWidth);
} else {
outStream.println("no modules found");
}
} else {
StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) {
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
throw ErrorUtil.createCommandException(e.getMessage());
}
payload = (MapValue) JSONParser.parse(result.toString());
throw ErrorUtil.createCommandException(payload.getStringValue("message"));
}
} finally {
conn.disconnect();
}
} | 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 |
protected abstract void saveXML(final String writerString) throws IOException ;
/**
* When this method is called users name is changed, so also is the username
* belonging to the group and the view. Also overwrites the "users.xml" file
*
* @param oldName a {@link java.lang.String} object.
* @param newName a {@link java.lang.String} object.
* @throws java.lang.Exception if any.
*/
public void renameUser(final String oldName, final String newName) throws Exception {
update();
m_writeLock.lock();
try {
// Get the old data
if (m_users.containsKey(oldName)) {
final User data = m_users.get(oldName);
if (data == null) {
m_users.remove(oldName);
throw new Exception("UserFactory:rename the data contained for old user " + oldName + " is null");
} else {
if (m_users.containsKey(newName)) {
throw new Exception("UserFactory: cannot rename user " + oldName + ". An user with the given name " + newName + " already exists");
}
// Rename the user in the user map.
m_users.remove(oldName);
data.setUserId(newName);
m_users.put(newName, data);
// Refresh the groups config first
m_groupManager.update();
// Rename the user in the group.
m_groupManager.renameUser(oldName, newName);
// Rename the user in the view.
// viewFactory.renameUser(oldName, newName);
}
} else {
throw new Exception("UserFactory:rename the old user name " + oldName + " is not found");
}
_saveCurrent();
} finally {
m_writeLock.unlock();
}
} | 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 RainbowParameters(int[] vi)
{
this.vi = vi;
checkParams();
} | 1 | Java | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
protected void setDispatchHandler(DispatchHandler dispatchHandler) {
this.dispatchHandler = dispatchHandler;
} | 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 translate(SetPlayerGameTypePacket packet, GeyserSession session) {
// no
SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket();
playerGameTypePacket.setGamemode(session.getGameMode().ordinal());
session.sendUpstreamPacket(playerGameTypePacket);
} | 0 | Java | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
public void testInvalidUserIds() {
testInvalidUserId("John<b>Doe</b>",true);
testInvalidUserId("Jane'Doe'",true);
testInvalidUserId("John&Doe",true);
testInvalidUserId("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 |
public void setPathSeparator(final String pathSeparator) {
this.pathSeparator = pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR;
} | 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 testSelectByOperations() {
JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyOperations(KeyOperation.SIGN, KeyOperation.VERIFY).build());
List<JWK> keyList = new ArrayList<>();
keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1")
.keyOperations(new HashSet<>(Arrays.asList(KeyOperation.SIGN, KeyOperation.VERIFY))).build());
keyList.add(new ECKey.Builder(ECKey.Curve.P_256, EC_P256_X, EC_P256_Y).keyID("2").build());
JWKSet jwkSet = new JWKSet(keyList);
List<JWK> matches = selector.select(jwkSet);
RSAKey key1 = (RSAKey)matches.get(0);
assertEquals(KeyType.RSA, key1.getKeyType());
assertEquals("1", key1.getKeyID());
assertEquals(1, matches.size());
} | 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 validateFail(ViolationCollector col) {
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public void translate(RiderJumpPacket packet, GeyserSession session) {
Entity vehicle = session.getRidingVehicleEntity();
if (vehicle instanceof AbstractHorseEntity) {
ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(), PlayerState.START_HORSE_JUMP, packet.getJumpStrength());
session.sendDownstreamPacket(playerStatePacket);
}
} | 0 | Java | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
public void testHeaderNameEndsWithControlChar1c() {
testHeaderNameEndsWithControlChar(0x1c);
} | 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 correctExample() {
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public void translate(PacketViolationWarningPacket packet, GeyserSession session) {
// Not translated since this is something that the developers need to know
session.getConnector().getLogger().error("Packet violation warning sent from client! " + packet.toString());
} | 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 |
protected void switchToConversation(Contact contact) {
Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
switchToConversation(conversation);
} | 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 static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException {
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;
}
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public static String getResponseMimeType(String pRequestMimeType, String defaultMimeType, String pCallback) {
// For a valid given callback, return "text/javascript" for proper inclusion
if (pCallback != null && isValidCallback(pCallback)) {
return "text/javascript";
}
// Pick up mime time from request, but sanitize
if (pRequestMimeType != null) {
return sanitize(pRequestMimeType);
}
// Use the given default mime type (possibly picked up from a configuration)
return sanitize(defaultMimeType);
} | 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 String getMimeType(HttpServletRequest pReq) {
String requestMimeType = pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue());
if (requestMimeType != null) {
return requestMimeType;
}
return configMimeType;
} | 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 qnameFail2() {
QName.get(":nselement", "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 testHeaderNameEndsWithControlChar1e() {
testHeaderNameEndsWithControlChar(0x1e);
} | 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 |
private TextBlock getTitleBlock(IGroup g) {
final Display label = g.getDisplay();
if (label == null)
return TextBlockUtils.empty(0, 0);
final ISkinParam skinParam = dotData.getSkinParam();
final FontConfiguration fontConfiguration;
if (UseStyle.useBetaStyle()) {
final SName sname = dotData.getUmlDiagramType().getStyleName();
final StyleSignatureBasic signature;
final USymbol uSymbol = g.getUSymbol();
if (uSymbol == USymbols.RECTANGLE)
signature = StyleSignatureBasic.of(SName.root, SName.element, sname, uSymbol.getSName(), SName.title);
else
signature = StyleSignatureBasic.of(SName.root, SName.element, sname, SName.title);
final Style style = signature //
.withTOBECHANGED(g.getStereotype()) //
.with(g.getStereostyles()) //
.getMergedStyle(skinParam.getCurrentStyleBuilder());
fontConfiguration = style.getFontConfiguration(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());
} else
fontConfiguration = g.getFontConfigurationForTitle(skinParam);
final HorizontalAlignment alignment = HorizontalAlignment.CENTER;
return label.create(fontConfiguration, alignment, dotData.getSkinParam());
} | 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 testMultiply1()
{
int COUNT = 1000;
for (int i = 0; i < COUNT; ++i)
{
ECFieldElement x = generateMultiplyInput_Random();
ECFieldElement y = generateMultiplyInput_Random();
BigInteger X = x.toBigInteger(), Y = y.toBigInteger();
BigInteger R = X.multiply(Y).mod(Q);
ECFieldElement z = x.multiply(y);
BigInteger Z = z.toBigInteger();
assertEquals(R, Z);
}
} | 1 | Java | CWE-19 | Data Processing Errors | Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information. | https://cwe.mitre.org/data/definitions/19.html | safe |
public SAXParser newSAXParser() throws ParserConfigurationException {
final SAXParser ret;
try {
ret = new XercesJAXPSAXParser(this, features, validating, handleXInclude);
} catch (final SAXException se) {
// Translate to ParserConfigurationException
throw new OXFException(se); // so we see a decent stack trace!
// throw new ParserConfigurationException(se.getMessage());
}
return ret;
} | 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 testSelectByUseNotSpecifiedOrSignature() {
JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyUses(KeyUse.SIGNATURE, null).build());
List<JWK> keyList = new ArrayList<>();
keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").keyUse(KeyUse.SIGNATURE).build());
keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build());
keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("3").keyUse(KeyUse.ENCRYPTION).build());
JWKSet jwkSet = new JWKSet(keyList);
List<JWK> matches = selector.select(jwkSet);
RSAKey key1 = (RSAKey)matches.get(0);
assertEquals(KeyType.RSA, key1.getKeyType());
assertEquals(KeyUse.SIGNATURE, key1.getKeyUse());
assertEquals("1", key1.getKeyID());
ECKey key2 = (ECKey)matches.get(1);
assertEquals(KeyType.EC, key2.getKeyType());
assertEquals("2", key2.getKeyID());
assertEquals(2, matches.size());
} | 0 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | vulnerable |
private DefaultHttpClient makeHttpClient() {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
try {
logger.debug("Installing forgiving hostname verifier and trust managers");
X509TrustManager trustManager = createTrustManager();
X509HostnameVerifier hostNameVerifier = createHostNameVerifier();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier);
ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
} catch (NoSuchAlgorithmException e) {
logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
} catch (KeyManagementException e) {
logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
}
return defaultHttpClient;
} | 0 | Java | CWE-346 | Origin Validation Error | The software does not properly verify that the source of data or communication is valid. | https://cwe.mitre.org/data/definitions/346.html | vulnerable |
public static JpaSort unsafe(Direction direction, List<String> properties) {
Assert.notEmpty(properties, "Properties must not be empty!");
List<Order> orders = new ArrayList<Order>();
for (String property : properties) {
orders.add(new JpaOrder(direction, property));
}
return new JpaSort(orders);
} | 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 test_notLike_startsWith() {
Entity from = from(Entity.class);
where(from.getCode()).notLike().startsWith("test");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where entity_0.code not like 'test%'", select.getQuery());
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public Document read(InputStream in, String systemId)
throws DocumentException {
InputSource source = new InputSource(in);
source.setSystemId(systemId);
if (this.encoding != null) {
source.setEncoding(this.encoding);
}
return read(source);
} | 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 allowECPFlow() {
return "true".equals(resolveAttribute(SamlConfigAttributes.SAML_ALLOW_ECP_FLOW));
} | 1 | Java | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
private Style getStyleState() {
return StyleSignatureBasic.of(SName.root, SName.element, SName.stateDiagram, SName.state).withTOBECHANGED(group.getStereotype())
.getMergedStyle(diagram.getSkinParam().getCurrentStyleBuilder());
} | 0 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
public static boolean isPointOnCurve(final ECPublicKey publicKey, final ECPrivateKey privateKey) {
return isPointOnCurve(publicKey, privateKey.getParams());
} | 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 static String printFormattedMetadata(final IBaseDataObject payload) {
final StringBuilder out = new StringBuilder();
out.append(LS);
for (final Map.Entry<String, Collection<Object>> entry : payload.getParameters().entrySet()) {
out.append(entry.getKey() + SEP + entry.getValue() + LS);
}
return out.toString();
} | 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 void handle(final HttpServletRequest request, final HttpServletResponse response)
throws Exception
{
new ContextualHttpServletRequest(request)
{
@Override
public void process() throws Exception
{
ServletContexts.instance().setRequest(request);
if (request.getQueryString() == null)
{
throw new ServletException("Invalid request - no component specified");
}
Set<Component> components = new HashSet<Component>();
Set<Type> types = new HashSet<Type>();
response.setContentType("text/javascript");
Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
String componentName = ((String) e.nextElement()).trim();
Component component = Component.forName(componentName);
if (component == null)
{
try
{
Class c = Reflections.classForName(componentName);
appendClassSource(response.getOutputStream(), c, types);
}
catch (ClassNotFoundException ex)
{
log.error(String.format("Component not found: [%s]", componentName));
throw new ServletException("Invalid request - component not found.");
}
}
else
{
components.add(component);
}
}
generateComponentInterface(components, response.getOutputStream(), types);
}
}.run();
} | 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 |
void testPointWithException() {
JsonParser.Defaults.classMetadataName = "__class";
JsonSerializer.Defaults.classMetadataName = "__class";
JsonParsers.forEachParser(jsonParser -> {
jsonParser.allowClass("notAllowed");
final String json = new JsonSerializer().serialize(new Point2D.Float(1.0f, 2.0f));
assertThrows(JsonException.class, () -> {
jsonParser.parse(json);
});
jsonParser.allowAllClasses();
});
} | 1 | Java | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
private ApiTokenProperty(String seed) {
apiToken = Secret.fromString(seed);
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public boolean matchStart(final String pattern, final String path) {
return doMatch(pattern, path, false);
} | 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 testSelectByOperationsNotSpecifiedOrSign() {
JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyOperations(KeyOperation.SIGN, null).build());
List<JWK> keyList = new ArrayList<>();
keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.SIGN))).build());
keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build());
keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("3")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.ENCRYPT))).build());
JWKSet jwkSet = new JWKSet(keyList);
List<JWK> matches = selector.select(jwkSet);
RSAKey key1 = (RSAKey)matches.get(0);
assertEquals(KeyType.RSA, key1.getKeyType());
assertEquals("1", key1.getKeyID());
ECKey key2 = (ECKey)matches.get(1);
assertEquals(KeyType.EC, key2.getKeyType());
assertEquals("2", key2.getKeyID());
assertEquals(2, matches.size());
} | 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 test_like_any() {
Entity from = from(Entity.class);
where(from.getCode()).like().any("test");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where entity_0.code like '%test%'", select.getQuery());
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private static void addMagic(SName sname) {
final String cleanName = sname.name().replace("_", "");
addConvert(cleanName + "BackgroundColor", PName.BackGroundColor, sname);
addConvert(cleanName + "BorderColor", PName.LineColor, sname);
addConvert(cleanName + "BorderThickness", PName.LineThickness, sname);
addConvert(cleanName + "RoundCorner", PName.RoundCorner, sname);
addConvert(cleanName + "DiagonalCorner", PName.DiagonalCorner, sname);
addConvert(cleanName + "BorderStyle", PName.LineStyle, sname);
addConvert(cleanName + "StereotypeFontColor", PName.FontColor, SName.stereotype, sname);
addConFont(cleanName, sname);
} | 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 translate(ServerStatisticsPacket packet, GeyserSession session) {
session.updateStatistics(packet.getStatistics());
if (session.isWaitingForStatistics()) {
session.setWaitingForStatistics(false);
StatisticsUtils.buildAndSendStatisticsMenu(session);
}
} | 0 | Java | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
public void removeUserDetailsFromOfflineCause() throws Exception {
Computer computer = j.jenkins.getComputer("deserialized");
verifyOfflineCause(computer);
} | 1 | Java | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
public void testGetChunk() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf1 = test.getChunk(1024);
assertEquals(buf1.readerIndex(), 0);
assertEquals(buf1.writerIndex(), 1024);
ByteBuf buf2 = test.getChunk(1024);
assertEquals(buf2.readerIndex(), 0);
assertEquals(buf2.writerIndex(), 1024);
assertFalse("Arrays should not be equal",
Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));
} finally {
test.delete();
}
} | 0 | Java | CWE-379 | Creation of Temporary File in Directory with Insecure Permissions | The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file. | https://cwe.mitre.org/data/definitions/379.html | vulnerable |
public 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 |
public static ByteBuffer serializeToByteBuffer(final Object payload) throws IOException {
return ByteBuffer.wrap(serializeToBytes(payload));
} | 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 void testValidGroupIds() {
testInvalidGroupId("John-Doe",false);
testInvalidGroupId("Jane/Doe",false);
testInvalidGroupId("John.Doe",false);
testInvalidGroupId("Jane#Doe", false);
testInvalidGroupId("John@Döe.com", false);
testInvalidGroupId("JohnDoé", false);
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
public void testMimeTypeApplicationJson() throws IOException, URISyntaxException {
checkMimeType("application/json", "application/json");
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
} catch (Exception e) {
} | 1 | Java | CWE-862 | Missing Authorization | The software does not perform an authorization check when an actor attempts to access a resource or perform an action. | https://cwe.mitre.org/data/definitions/862.html | safe |
public RFC5649Wrap()
{
super(new RFC5649WrapEngine(new AESFastEngine()));
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
private LikeCondition createLike(Type type, String toMatch) {
if (notLike) {
return new NotLikeCondition(selector, selector.generateParameter(type.wrap(toMatch)));
} else {
return new LikeCondition(selector, selector.generateParameter(type.wrap(toMatch)));
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
const SaplingEncCiphertext &ciphertext,
const uint256 &epk,
const uint256 &esk,
const uint256 &pk_d,
const uint256 &cmu
)
{
auto pt = AttemptSaplingEncDecryption(ciphertext, epk, esk, pk_d);
if (!pt) {
return boost::none;
}
// Deserialize from the plaintext
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pt.get();
SaplingNotePlaintext ret;
ss >> ret;
uint256 cmu_expected;
if (!librustzcash_sapling_compute_cm(
ret.d.data(),
pk_d.begin(),
ret.value(),
ret.rcm.begin(),
cmu_expected.begin()
))
{
return boost::none;
}
if (cmu_expected != cmu) {
return boost::none;
}
assert(ss.size() == 0);
return ret;
} | 0 | C++ | 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 | vulnerable |
void TensorSliceReader::LoadShard(int shard) const {
CHECK_LT(shard, sss_.size());
if (sss_[shard] || !status_.ok()) {
return; // Already loaded, or invalid.
}
string value;
SavedTensorSlices sts;
const string fname = fnames_[shard];
VLOG(1) << "Reading meta data from file " << fname << "...";
Table* table;
Status s = open_function_(fname, &table);
if (!s.ok()) {
status_ = errors::DataLoss("Unable to open table file ", fname, ": ",
s.ToString());
return;
}
sss_[shard].reset(table);
if (!(table->Get(kSavedTensorSlicesKey, &value) &&
ParseProtoUnlimited(&sts, value))) {
status_ = errors::Internal(
"Failed to find the saved tensor slices at the beginning of the "
"checkpoint file: ",
fname);
return;
}
status_ = CheckVersions(sts.meta().versions(), TF_CHECKPOINT_VERSION,
TF_CHECKPOINT_VERSION_MIN_PRODUCER, "Checkpoint",
"checkpoint");
if (!status_.ok()) return;
for (const SavedSliceMeta& ssm : sts.meta().tensor()) {
TensorShape ssm_shape;
status_ = TensorShape::BuildTensorShapeBase(ssm.shape(), &ssm_shape);
if (!status_.ok()) return;
for (const TensorSliceProto& tsp : ssm.slice()) {
TensorSlice ss_slice(tsp);
status_ = RegisterTensorSlice(ssm.name(), ssm_shape, ssm.type(), fname,
ss_slice, &tensors_);
if (!status_.ok()) return;
}
}
} | 0 | C++ | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | vulnerable |
int jas_matrix_resize(jas_matrix_t *matrix, jas_matind_t numrows,
jas_matind_t numcols)
{
jas_matind_t size;
jas_matind_t i;
size = numrows * numcols;
if (size > matrix->datasize_ || numrows > matrix->maxrows_) {
return -1;
}
matrix->numrows_ = numrows;
matrix->numcols_ = numcols;
for (i = 0; i < numrows; ++i) {
matrix->rows_[i] = &matrix->data_[numcols * i];
}
return 0;
} | 1 | C++ | 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 |
int64_t length() const {
return m_str ? m_str->size() : 0;
} | 1 | C++ | 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 | safe |
TfLiteStatus EvalLogic(TfLiteContext* context, TfLiteNode* node,
OpContext* op_context, T init_value,
T reducer(const T current, const T in)) {
int64_t num_axis = NumElements(op_context->axis);
TfLiteTensor* temp_index;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, /*index=*/0, &temp_index));
TfLiteTensor* resolved_axis;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, /*index=*/1, &resolved_axis));
// Resize the output tensor if the output tensor is dynamic.
if (IsDynamicTensor(op_context->output)) {
TF_LITE_ENSURE_OK(context,
ResizeTempAxis(context, op_context, resolved_axis));
TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, op_context));
}
if (op_context->input->type == kTfLiteUInt8 ||
op_context->input->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, op_context->input->params.scale,
op_context->output->params.scale);
TF_LITE_ENSURE_EQ(context, op_context->input->params.zero_point,
op_context->output->params.zero_point);
}
TF_LITE_ENSURE(
context,
reference_ops::ReduceGeneric<T>(
GetTensorData<T>(op_context->input), op_context->input->dims->data,
op_context->input->dims->size, GetTensorData<T>(op_context->output),
op_context->output->dims->data, op_context->output->dims->size,
GetTensorData<int>(op_context->axis), num_axis,
op_context->params->keep_dims, GetTensorData<int>(temp_index),
GetTensorData<int>(resolved_axis), init_value, reducer));
return kTfLiteOk;
} | 1 | C++ | 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 | safe |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
switch (output->type) {
case kTfLiteFloat32: {
return ReverseSequenceHelper<float>(context, node);
}
case kTfLiteUInt8: {
return ReverseSequenceHelper<uint8_t>(context, node);
}
case kTfLiteInt16: {
return ReverseSequenceHelper<int16_t>(context, node);
}
case kTfLiteInt32: {
return ReverseSequenceHelper<int32_t>(context, node);
}
case kTfLiteInt64: {
return ReverseSequenceHelper<int64_t>(context, node);
}
default: {
context->ReportError(context,
"Type '%s' is not supported by reverse_sequence.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} // namespace | 1 | C++ | 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 | safe |
void Compute(OpKernelContext* context) override {
const Tensor& tensor_in = context->input(0);
const Tensor& tensor_out = context->input(1);
const Tensor& out_grad_backprop = context->input(2);
// For maxpooling3d, tensor_in should have 5 dimensions.
OP_REQUIRES(context, tensor_in.dims() == 5,
errors::InvalidArgument("tensor_in must be 5-dimensional"));
OP_REQUIRES(context, tensor_out.dims() == 5,
errors::InvalidArgument("tensor_out must be 5-dimensional"));
// For maxpooling3d, out_grad_backprop should have 5 dimensions.
OP_REQUIRES(
context, out_grad_backprop.dims() == 5,
errors::InvalidArgument("out_grad_backprop must be 5-dimensional"));
Pool3dParameters params{context, ksize_, stride_,
padding_, data_format_, tensor_in.shape()};
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{2}, 0, tensor_out.shape(), &output));
// Given access patterns in LaunchMaxPooling3dGradGradOp, these tensors must
// have elements.
OP_REQUIRES(context, tensor_in.NumElements() > 0,
errors::InvalidArgument("received empty tensor tensor_in: ",
tensor_in.DebugString()));
OP_REQUIRES(context, tensor_out.NumElements() > 0,
errors::InvalidArgument("received empty tensor tensor_out: ",
tensor_out.DebugString()));
OP_REQUIRES(
context, out_grad_backprop.NumElements() > 0,
errors::InvalidArgument("received empty tensor out_grad_backprop: ",
out_grad_backprop.DebugString()));
LaunchMaxPooling3dGradGradOp<Device, T>::launch(
context, params, tensor_in, tensor_out, out_grad_backprop, output);
} | 1 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
void PCRECache::dump(folly::File& file) {
switch (m_kind) {
case CacheKind::Static:
for (auto& it : *m_staticCache) {
folly::writeFull(file.fd(), it.first->data(), it.first->size());
folly::writeFull(file.fd(), "\n", 1);
}
break;
case CacheKind::Lru:
case CacheKind::Scalable:
{
std::vector<LRUCacheKey> keys;
if (m_kind == CacheKind::Lru) {
m_lruCache->snapshotKeys(keys);
} else {
m_scalableCache->snapshotKeys(keys);
}
for (auto& key: keys) {
folly::writeFull(file.fd(), key.data(), key.size());
folly::writeFull(file.fd(), "\n", 1);
}
}
break;
}
} | 1 | C++ | 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 | safe |
StatusOr<FullTypeDef> SpecializeType(const AttrSlice& attrs,
const OpDef& op_def) {
FullTypeDef ft;
ft.set_type_id(TFT_PRODUCT);
for (int i = 0; i < op_def.output_arg_size(); i++) {
auto* t = ft.add_args();
*t = op_def.output_arg(i).experimental_full_type();
// Resolve dependent types. The convention for op registrations is to use
// attributes as type variables.
// See https://www.tensorflow.org/guide/create_op#type_polymorphism.
// Once the op signature can be defined entirely in FullType, this
// convention can be deprecated.
//
// Note: While this code performs some basic verifications, it generally
// assumes consistent op defs and attributes. If more complete
// verifications are needed, they should be done by separately, and in a
// way that can be reused for type inference.
for (int j = 0; j < t->args_size(); j++) {
auto* arg = t->mutable_args(i);
if (arg->type_id() == TFT_VAR) {
const auto* attr = attrs.Find(arg->s());
if (attr == nullptr) {
return Status(
error::INVALID_ARGUMENT,
absl::StrCat("Could not find an attribute for key ", arg->s()));
}
if (attr->value_case() == AttrValue::kList) {
const auto& attr_list = attr->list();
arg->set_type_id(TFT_PRODUCT);
for (int i = 0; i < attr_list.type_size(); i++) {
map_dtype_to_tensor(attr_list.type(i), arg->add_args());
}
} else if (attr->value_case() == AttrValue::kType) {
map_dtype_to_tensor(attr->type(), arg);
} else {
return Status(error::UNIMPLEMENTED,
absl::StrCat("unknown attribute type",
attrs.DebugString(), " key=", arg->s()));
}
arg->clear_s();
}
}
}
return ft;
} | 0 | C++ | 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 |
inline TfLiteStatus GetMutableInputSafe(const TfLiteContext* context,
const TfLiteNode* node, int index,
const TfLiteTensor** tensor) {
int tensor_index;
TF_LITE_ENSURE_OK(
context, ValidateTensorIndexingSafe(context, index, node->inputs->size,
node->inputs->data, &tensor_index));
*tensor = GetTensorAtIndex(context, tensor_index);
return kTfLiteOk;
} | 1 | C++ | 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 | safe |
static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
// Compute the number of samples in the image component, while protecting
// against overflow.
// size = cmpt->width_ * cmpt->height_ * cmpt->cps_;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
return 0;
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
Pl_ASCIIHexDecoder::flush()
{
if (this->pos == 0)
{
QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush");
return;
}
int b[2];
for (int i = 0; i < 2; ++i)
{
if (this->inbuf[i] >= 'A')
{
b[i] = this->inbuf[i] - 'A' + 10;
}
else
{
b[i] = this->inbuf[i] - '0';
}
}
unsigned char ch = static_cast<unsigned char>((b[0] << 4) + b[1]);
QTC::TC("libtests", "Pl_ASCIIHexDecoder partial flush",
(this->pos == 2) ? 0 : 1);
// Reset before calling getNext()->write in case that throws an
// exception.
this->pos = 0;
this->inbuf[0] = '0';
this->inbuf[1] = '0';
this->inbuf[2] = '\0';
getNext()->write(&ch, 1);
} | 1 | C++ | 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 | safe |
Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,
int input_index) {
if (output_index >= src->num_outputs()) {
return errors::InvalidArgument(
"Output ", output_index, " of node ", src->name(),
" does not exist. Node only has ", src->num_outputs(), " outputs.");
}
if (input_index >= dst->num_inputs()) {
return errors::InvalidArgument(
"Input ", input_index, " of node ", dst->name(),
" does not exist. Node only has ", dst->num_inputs(), " inputs.");
}
DataType src_out = src->output_type(output_index);
DataType dst_in = dst->input_type(input_index);
if (!TypesCompatible(dst_in, src_out)) {
return errors::InvalidArgument(
"Input ", input_index, " of node ", dst->name(), " was passed ",
DataTypeString(src_out), " from ", src->name(), ":", output_index,
" incompatible with expected ", DataTypeString(dst_in), ".");
}
g_->AddEdge(src, output_index, dst, input_index);
return Status::OK();
} | 1 | C++ | CWE-908 | Use of Uninitialized Resource | The software uses or accesses a resource that has not been initialized. | https://cwe.mitre.org/data/definitions/908.html | safe |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
TfLiteTensor* output = GetOutput(context, node, 0);
TfLiteTensor* hits = GetOutput(context, node, 1);
const TfLiteTensor* lookup = GetInput(context, node, 0);
const TfLiteTensor* key = GetInput(context, node, 1);
const TfLiteTensor* value = GetInput(context, node, 2);
const int num_rows = SizeOfDimension(value, 0);
const int row_bytes = value->bytes / num_rows;
void* pointer = nullptr;
DynamicBuffer buf;
for (int i = 0; i < SizeOfDimension(lookup, 0); i++) {
int idx = -1;
pointer = bsearch(&(lookup->data.i32[i]), key->data.i32, num_rows,
sizeof(int32_t), greater);
if (pointer != nullptr) {
idx = (reinterpret_cast<char*>(pointer) - (key->data.raw)) /
sizeof(int32_t);
}
if (idx >= num_rows || idx < 0) {
if (output->type == kTfLiteString) {
buf.AddString(nullptr, 0);
} else {
memset(output->data.raw + i * row_bytes, 0, row_bytes);
}
hits->data.uint8[i] = 0;
} else {
if (output->type == kTfLiteString) {
buf.AddString(GetString(value, idx));
} else {
memcpy(output->data.raw + i * row_bytes,
value->data.raw + idx * row_bytes, row_bytes);
}
hits->data.uint8[i] = 1;
}
}
if (output->type == kTfLiteString) {
buf.WriteToTensorAsVector(output);
}
return kTfLiteOk;
} | 0 | C++ | 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 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
const int num_elements = NumElements(input);
switch (input->type) {
case kTfLiteInt64:
memset(GetTensorData<int64_t>(output), 0, num_elements * sizeof(int64_t));
break;
case kTfLiteInt32:
memset(GetTensorData<int32_t>(output), 0, num_elements * sizeof(int32_t));
break;
case kTfLiteFloat32:
memset(GetTensorData<float>(output), 0, num_elements * sizeof(float));
break;
default:
context->ReportError(context,
"ZerosLike only currently supports int64, int32, "
"and float32, got %d.",
input->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | 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 |
TEST(BasicFlatBufferModel, TestUnsupportedRecursion) {
const auto model_path =
"tensorflow/lite/testdata/unsupported_recursion.bin";
std::unique_ptr<tflite::FlatBufferModel> model =
FlatBufferModel::BuildFromFile(model_path);
ASSERT_NE(model, nullptr);
tflite::ops::builtin::BuiltinOpResolver resolver;
InterpreterBuilder builder(*model, resolver);
std::unique_ptr<Interpreter> interpreter;
ASSERT_EQ(builder(&interpreter), kTfLiteOk);
ASSERT_NE(interpreter, nullptr);
ASSERT_NE(interpreter->AllocateTensors(), kTfLiteOk);
} | 1 | C++ | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
static inline long decode_twos_comp(ulong c, int prec)
{
long result;
assert(prec >= 2);
jas_eprintf("warning: support for signed data is untested\n");
// NOTE: Is this correct?
result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1)));
return result;
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
TEST(DefaultCertValidatorTest, TestMatchSubjectAltNameURIMatched) {
bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute(
"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem"));
envoy::type::matcher::v3::StringMatcher matcher;
matcher.MergeFrom(TestUtility::createRegexMatcher("spiffe://lyft.com/.*-team"));
std::vector<Matchers::StringMatcherImpl<envoy::type::matcher::v3::StringMatcher>>
subject_alt_name_matchers;
subject_alt_name_matchers.push_back(Matchers::StringMatcherImpl(matcher));
EXPECT_TRUE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers));
} | 0 | C++ | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | vulnerable |
char *uwsgi_expand_path(char *dir, int dir_len, char *ptr) {
if (dir_len > PATH_MAX)
{
uwsgi_log("invalid path size: %d (max %d)\n", dir_len, PATH_MAX);
return NULL;
}
char *src = uwsgi_concat2n(dir, dir_len, "", 0);
char *dst = ptr;
if (!dst)
dst = uwsgi_malloc(PATH_MAX + 1);
if (!realpath(src, dst)) {
uwsgi_error_realpath(src);
if (!ptr)
free(dst);
free(src);
return NULL;
}
free(src);
return dst;
} | 1 | C++ | 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 | safe |
TfLiteStatus EqualEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
bool requires_broadcast = !HaveSameShapes(input1, input2);
switch (input1->type) {
case kTfLiteBool:
Comparison<bool, reference_ops::EqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteFloat32:
Comparison<float, reference_ops::EqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt32:
Comparison<int32_t, reference_ops::EqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt64:
Comparison<int64_t, reference_ops::EqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteUInt8:
ComparisonQuantized<uint8_t, reference_ops::EqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteInt8:
ComparisonQuantized<int8_t, reference_ops::EqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteString:
ComparisonString(reference_ops::StringRefEqualFn, input1, input2, output,
requires_broadcast);
break;
default:
context->ReportError(
context,
"Does not support type %d, requires bool|float|int|uint8|string",
input1->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 1 | C++ | 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 | safe |
static ssize_t _hostsock_recvmsg(
oe_fd_t* sock_,
struct oe_msghdr* msg,
int flags)
{
ssize_t ret = -1;
sock_t* sock = _cast_sock(sock_);
oe_errno = 0;
void* buf = NULL;
size_t buf_size = 0;
/* Check the parameters. */
if (!sock || !msg || (msg->msg_iovlen && !msg->msg_iov))
OE_RAISE_ERRNO(OE_EINVAL);
/* Flatten the IO vector into contiguous heap memory. */
if (oe_iov_pack(msg->msg_iov, (int)msg->msg_iovlen, &buf, &buf_size) != 0)
OE_RAISE_ERRNO(OE_ENOMEM);
/* Call the host. */
{
if (oe_syscall_recvmsg_ocall(
&ret,
sock->host_fd,
msg->msg_name,
msg->msg_namelen,
&msg->msg_namelen,
buf,
msg->msg_iovlen,
buf_size,
msg->msg_control,
msg->msg_controllen,
&msg->msg_controllen,
flags) != OE_OK)
{
OE_RAISE_ERRNO(OE_EINVAL);
}
if (ret == -1)
OE_RAISE_ERRNO(oe_errno);
}
/* Synchronize data read with IO vector. */
if (oe_iov_sync(msg->msg_iov, (int)msg->msg_iovlen, buf, buf_size) != 0)
OE_RAISE_ERRNO(OE_EINVAL);
done:
if (buf)
oe_free(buf);
return ret;
} | 0 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* cond_tensor =
GetInput(context, node, kInputConditionTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (cond_tensor->type != kTfLiteBool) {
context->ReportError(context,
"Condition tensor must be of type bool, but saw '%s'.",
TfLiteTypeGetName(cond_tensor->type));
return kTfLiteError;
}
// As output will be a 2D tensor of indices, use int64 to be consistent with
// tensorflow.
output->type = kTfLiteInt64;
// Exit early if cond is a non-const tensor. Set output tensor to dynamic so
// output size can be determined in Eval.
if (!IsConstantTensor(cond_tensor)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
return ResizeOutputTensor(context, cond_tensor, output);
} | 0 | C++ | 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 |
std::string encodeBase64(const std::string& input) {
using namespace boost::archive::iterators;
using b64it = base64_from_binary<transform_width<const char*, 6, 8>>;
auto data = input.data();
std::string encoded(b64it(data), b64it(data + (input.length())));
encoded.append((3 - (input.length() % 3)) % 3, '=');
return encoded;
} | 0 | C++ | 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 |
static int bson_append_string_base( bson *b, const char *name,
const char *value, int len, bson_type type ) {
int sl = len + 1;
if ( bson_check_string( b, ( const char * )value, sl - 1 ) == BSON_ERROR )
return BSON_ERROR;
if ( bson_append_estart( b, type, name, 4 + sl ) == BSON_ERROR ) {
return BSON_ERROR;
}
bson_append32( b , &sl );
bson_append( b , value , sl - 1 );
bson_append( b , "\0" , 1 );
return BSON_OK;
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)
{
Q_UNUSED(bufferInfo);
if (!msg.contains(' '))
return;
QString target = msg.section(' ', 0, 0);
QByteArray encMsg = userEncode(target, msg.section(' ', 1));
#ifdef HAVE_QCA2
putPrivmsg(serverEncode(target), encMsg, network()->cipher(target));
#else
putPrivmsg(serverEncode(target), encMsg);
#endif
} | 0 | C++ | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | https://cwe.mitre.org/data/definitions/399.html | vulnerable |
bool SPIFFEValidator::matchSubjectAltName(X509& leaf_cert) {
bssl::UniquePtr<GENERAL_NAMES> san_names(static_cast<GENERAL_NAMES*>(
X509_get_ext_d2i(&leaf_cert, NID_subject_alt_name, nullptr, nullptr)));
// We must not have san_names == nullptr here because this function is called after the
// SPIFFE cert validation algorithm succeeded, which requires exactly one URI SAN in the leaf
// cert.
ASSERT(san_names != nullptr,
"san_names should have at least one name after SPIFFE cert validation");
// Only match against URI SAN since SPIFFE specification does not restrict values in other SAN
// types. See the discussion: https://github.com/envoyproxy/envoy/issues/15392
for (const GENERAL_NAME* general_name : san_names.get()) {
if (general_name->type == GEN_URI) {
const std::string san = Utility::generalNameAsString(general_name);
for (const auto& config_san_matcher : subject_alt_name_matchers_) {
if (config_san_matcher.match(san)) {
return true;
}
}
}
}
return false;
} | 0 | C++ | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | vulnerable |
bool AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride,
int pad_width, int pad_height, int filter_width,
int filter_height, int32 output_activation_min,
int32 output_activation_max, uint8* output_data,
const Dims<4>& output_dims) {
return AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width,
pad_height, filter_width, filter_height,
output_activation_min, output_activation_max,
output_data, output_dims);
} | 1 | C++ | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
Statement::BindParameter(const Napi::Value source, T pos) {
if (source.IsString()) {
std::string val = source.As<Napi::String>().Utf8Value();
return new Values::Text(pos, val.length(), val.c_str());
}
else if (OtherInstanceOf(source.As<Object>(), "RegExp")) {
std::string val = source.ToString().Utf8Value();
return new Values::Text(pos, val.length(), val.c_str());
}
else if (source.IsNumber()) {
if (OtherIsInt(source.As<Napi::Number>())) {
return new Values::Integer(pos, source.As<Napi::Number>().Int32Value());
} else {
return new Values::Float(pos, source.As<Napi::Number>().DoubleValue());
}
}
else if (source.IsBoolean()) {
return new Values::Integer(pos, source.As<Napi::Boolean>().Value() ? 1 : 0);
}
else if (source.IsNull()) {
return new Values::Null(pos);
}
else if (source.IsBuffer()) {
Napi::Buffer<char> buffer = source.As<Napi::Buffer<char>>();
return new Values::Blob(pos, buffer.Length(), buffer.Data());
}
else if (OtherInstanceOf(source.As<Object>(), "Date")) {
return new Values::Float(pos, source.ToNumber().DoubleValue());
}
else if (source.IsObject()) {
std::string val = source.ToString().Utf8Value();
return new Values::Text(pos, val.length(), val.c_str());
}
else {
return NULL;
}
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
bool HHVM_FUNCTION(apc_store_as_primed_do_not_use,
const String& key,
const Variant& var) {
if (!apcExtension::Enable) return false;
if (isKeyInvalid(key)) {
throw_invalid_argument("apc key: (contains invalid characters)");
return false;
}
apc_store().setWithoutTTL(key, var);
return true;
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
return r;
} | 0 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | vulnerable |
MONGO_EXPORT int bson_finish( bson *b ) {
int i;
if( b->err & BSON_NOT_UTF8 )
return BSON_ERROR;
if ( ! b->finished ) {
if ( bson_ensure_space( b, 1 ) == BSON_ERROR ) return BSON_ERROR;
bson_append_byte( b, 0 );
i = b->cur - b->data;
bson_little_endian32( b->data, &i );
b->finished = 1;
}
return BSON_OK;
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
bool CModules::GetModInfo(CModInfo& ModInfo, const CString& sModule,
CString& sRetMsg) {
if (!ValidateModuleName(sModule, sRetMsg)) {
return false;
}
CString sModPath, sTmp;
bool bSuccess;
bool bHandled = false;
GLOBALMODULECALL(OnGetModInfo(ModInfo, sModule, bSuccess, sRetMsg),
&bHandled);
if (bHandled) return bSuccess;
if (!FindModPath(sModule, sModPath, sTmp)) {
sRetMsg = t_f("Unable to find module {1}.")(sModule);
return false;
}
return GetModPathInfo(ModInfo, sModule, sModPath, sRetMsg);
} | 1 | C++ | 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 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
if (type == kGenericOptimized) {
optimized_ops::Floor(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
} else {
reference_ops::Floor(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
}
return kTfLiteOk;
} | 1 | C++ | 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 | safe |
static inline void assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst)
{
switch (ctxt->op_bytes) {
case 2:
ctxt->_eip = (u16)dst;
break;
case 4:
ctxt->_eip = (u32)dst;
break;
case 8:
ctxt->_eip = dst;
break;
default:
WARN(1, "unsupported eip assignment size\n");
}
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
TfLiteStatus ResizeOutputTensors(TfLiteContext* context, TfLiteNode* node,
const TfLiteTensor* axis,
const TfLiteTensor* input, int num_splits) {
int axis_value = GetTensorData<int>(axis)[0];
if (axis_value < 0) {
axis_value += NumDimensions(input);
}
TF_LITE_ENSURE(context, axis_value >= 0);
TF_LITE_ENSURE(context, axis_value < NumDimensions(input));
const int input_size = SizeOfDimension(input, axis_value);
TF_LITE_ENSURE(context, num_splits != 0);
TF_LITE_ENSURE_MSG(context, input_size % num_splits == 0,
"Not an even split");
const int slice_size = input_size / num_splits;
for (int i = 0; i < NumOutputs(node); ++i) {
TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims);
output_dims->data[axis_value] = slice_size;
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &output));
TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_dims));
}
return kTfLiteOk;
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
inline static bool jas_safe_intfast32_mul3(int_fast32_t a, int_fast32_t b,
int_fast32_t c, int_fast32_t *result)
{
int_fast32_t tmp;
if (!jas_safe_intfast32_mul(a, b, &tmp) ||
!jas_safe_intfast32_mul(tmp, c, &tmp)) {
return false;
}
if (result) {
*result = tmp;
}
return true;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
bool WddxPacket::recursiveAddVar(const String& varName,
const Variant& varVariant,
bool hasVarTag) {
SeenContainers seen;
return recursiveAddVarImpl(varName, varVariant, hasVarTag, seen);
} | 1 | C++ | 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 |
String string_chunk_split(const char *src, int srclen, const char *end,
int endlen, int chunklen) {
int chunks = srclen / chunklen; // complete chunks!
int restlen = srclen - chunks * chunklen; /* srclen % chunklen */
int out_len = (chunks + 1) * endlen + srclen;
String ret(out_len, ReserveString);
char *dest = ret.bufferSlice().ptr;
const char *p; char *q;
const char *pMax = src + srclen - chunklen + 1;
for (p = src, q = dest; p < pMax; ) {
memcpy(q, p, chunklen);
q += chunklen;
memcpy(q, end, endlen);
q += endlen;
p += chunklen;
}
if (restlen) {
memcpy(q, p, restlen);
q += restlen;
memcpy(q, end, endlen);
q += endlen;
}
ret.setSize(q - dest);
return ret;
} | 0 | C++ | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | https://cwe.mitre.org/data/definitions/189.html | vulnerable |
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y]);
}
}
} | 0 | C++ | CWE-908 | Use of Uninitialized Resource | The software uses or accesses a resource that has not been initialized. | https://cwe.mitre.org/data/definitions/908.html | vulnerable |
TEST_F(SingleAllowMissingInOrListTest, MissingIssToken) {
EXPECT_CALL(mock_cb_, onComplete(Status::Ok));
auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, ES256WithoutIssToken}};
context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);
verifier_->verify(context_);
EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kExampleHeader));
} | 0 | C++ | 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 |
static int parseFileInner(MaState *state, cchar *path)
{
MaDirective *directive;
char *tok, *key, *line, *value;
assert(state);
assert(path && *path);
if (openConfig(state, path) < 0) {
return MPR_ERR_CANT_OPEN;
}
for (state->lineNumber = 1; state->file && (line = mprReadLine(state->file, 0, NULL)) != 0; state->lineNumber++) {
for (tok = line; isspace((uchar) *tok); tok++) ;
if (*tok == '\0' || *tok == '#') {
continue;
}
state->key = 0;
if ((key = getDirective(line, &value)) == 0) {
continue;
}
if (!state->enabled) {
if (key[0] != '<') {
continue;
}
}
if ((directive = mprLookupKey(directives, key)) == 0) {
mprLog("error appweb config", 0, "Unknown directive \"%s\". At line %d in %s",
key, state->lineNumber, state->filename);
return MPR_ERR_BAD_SYNTAX;
}
state->key = key;
/*
Allow directives to run commands and yield without worring about holding references.
*/
mprPauseGC();
if ((*directive)(state, key, value) < 0) {
mprResumeGC();
mprLog("error appweb config", 0, "Error with directive \"%s\". At line %d in %s",
state->key, state->lineNumber, state->filename);
return MPR_ERR_BAD_SYNTAX;
}
mprResumeGC();
mprYield(0);
state = state->top->current;
}
/* EOF */
if (state->prev && state->file == state->prev->file) {
mprLog("error appweb config", 0, "Unclosed directives in %s", state->filename);
while (state->prev && state->file == state->prev->file) {
state = state->prev;
}
}
mprCloseFile(state->file);
return 0;
} | 1 | C++ | 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 |
R_API RBinJavaAttrInfo *r_bin_java_rtv_annotations_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
ut64 offset = 0;
if (buf_offset + 8 > sz) {
return NULL;
}
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR;
attr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free);
for (i = 0; i < attr->info.annotation_array.num_annotations; i++) {
if (offset >= sz) {
break;
}
RBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset);
if (annotation) {
offset += annotation->size;
r_list_append (attr->info.annotation_array.annotations, (void *) annotation);
}
}
attr->size = offset;
}
return attr;
} | 0 | C++ | CWE-805 | Buffer Access with Incorrect Length Value | The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer. | https://cwe.mitre.org/data/definitions/805.html | vulnerable |
CmdResult ShowSilenceList(LocalUser* user)
{
SilenceList* list = ext.get(user);
if (list)
{
for (SilenceList::const_iterator iter = list->begin(); iter != list->end(); ++iter)
{
user->WriteNumeric(RPL_SILELIST, iter->mask, SilenceEntry::BitsToFlags(iter->flags));
}
}
user->WriteNumeric(RPL_ENDOFSILELIST, "End of silence list");
return CMD_SUCCESS;
} | 1 | C++ | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | safe |
int pos() { return ptr - start; } | 0 | C++ | 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 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, 0);
TF_LITE_ENSURE(context, input != nullptr);
TfLiteTensor* output = GetOutput(context, node, 0);
TF_LITE_ENSURE(context, output != nullptr);
// TODO(b/128934713): Add support for fixed-point per-channel quantization.
// Currently this only support affine per-layer quantization.
TF_LITE_ENSURE_EQ(context, output->quantization.type,
kTfLiteAffineQuantization);
const auto* affine_quantization =
reinterpret_cast<TfLiteAffineQuantization*>(output->quantization.params);
TF_LITE_ENSURE(context, affine_quantization);
TF_LITE_ENSURE(context, affine_quantization->scale);
TF_LITE_ENSURE(context, affine_quantization->scale->size == 1);
TF_LITE_ENSURE(context, input->type == kTfLiteFloat32 ||
input->type == kTfLiteInt16 ||
input->type == kTfLiteInt8);
TF_LITE_ENSURE(context, output->type == kTfLiteUInt8 ||
output->type == kTfLiteInt8 ||
output->type == kTfLiteInt16);
if (((input->type == kTfLiteInt16 || input->type == kTfLiteInt8) &&
output->type == kTfLiteInt8) ||
(input->type == kTfLiteInt16 && output->type == kTfLiteInt16)) {
double effective_scale = static_cast<double>(input->params.scale) /
static_cast<double>(output->params.scale);
QuantizeMultiplier(effective_scale, &data->output_multiplier,
&data->output_shift);
}
data->quantization_params.zero_point = output->params.zero_point;
data->quantization_params.scale = static_cast<double>(output->params.scale);
data->input_zero_point = input->params.zero_point;
return kTfLiteOk;
} | 1 | C++ | 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 | safe |
void Compute(OpKernelContext* ctx) override {
const Tensor& values_tensor = ctx->input(0);
const Tensor& value_range_tensor = ctx->input(1);
const Tensor& nbins_tensor = ctx->input(2);
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(value_range_tensor.shape()),
errors::InvalidArgument("value_range should be a vector."));
OP_REQUIRES(ctx, (value_range_tensor.shape().num_elements() == 2),
errors::InvalidArgument(
"value_range should be a vector of 2 elements."));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(nbins_tensor.shape()),
errors::InvalidArgument("nbins should be a scalar."));
const auto values = values_tensor.flat<T>();
const auto value_range = value_range_tensor.flat<T>();
const auto nbins = nbins_tensor.scalar<int32>()();
OP_REQUIRES(
ctx, value_range(0) < value_range(1),
errors::InvalidArgument("value_range should satisfy value_range[0] < "
"value_range[1], but got '[",
value_range(0), ", ", value_range(1), "]'"));
OP_REQUIRES(
ctx, nbins > 0,
errors::InvalidArgument("nbins should be a positive number, but got '",
nbins, "'"));
Tensor* out_tensor;
OP_REQUIRES_OK(ctx,
ctx->allocate_output(0, TensorShape({nbins}), &out_tensor));
auto out = out_tensor->flat<Tout>();
OP_REQUIRES_OK(
ctx, functor::HistogramFixedWidthFunctor<Device, T, Tout>::Compute(
ctx, values, value_range, nbins, out));
} | 1 | C++ | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.