deardaniel/secdata-raw huggingface dataset:
CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')

Description:
The product uses XML documents and allows their structure to be defined with a Document Type Definition (DTD), but it does not properly control the number of recursive definitions of entities.

Extended Description:
If the DTD contains a large number of nested or recursive entities, this can lead to explosive growth of data when parsed, causing a denial of service.

Affected languages: Not Language-Specific, XML
Affected technologies: Not Technology-Specific
Parent weaknesses: CWE-674, CWE-674, CWE-405

Consequences:
  - Availability: DoS: Resource Consumption (Other)

Detection methods:
  - Automated Static Analysis: Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without havin

Mitigations:
  - [Operation] If possible, prohibit the use of DTDs or use an XML parser that limits the expansion of recursive DTD entities.
  - [Implementation] Before parsing XML files with associated DTDs, scan for recursive entity declarations and do not continue parsing potentially explosive content.

Demonstrative examples:
The DTD and the very brief XML below illustrate what is meant by an XML bomb. The ZERO entity contains one character, the letter A. The choice of entity name ZERO is being used to indicate length equivalent to that exponent on two, that is, the length of ZERO is 2^0. Similarly, ONE refers to ZERO twice, therefore the XML parser will expand ONE to a length of 2, or 2^1. Ultimately, we reach entity THIRTYTWO, which will expand to 2^32 characters in length, or 4 GB, probably consuming far more data than expected.

<?xml version="1.0"?> <!DOCTYPE MaliciousDTD [ <!ENTITY ZERO "A"> <!ENTITY ONE "&ZERO;&ZERO;"> <!ENTITY TWO "&ONE;&ONE;"> ... <!ENTITY THIRTYTWO "&THIRTYONE;&THIRTYONE;"> ]> <data>&THIRTYTWO;</data>

Real-world examples:
  - CVE-2008-3281: XEE in XML-parsing library.
  - CVE-2011-3288: XML bomb / XEE in enterprise communication product.
  - CVE-2011-1755: "Billion laughs" attack in XMPP server daemon.
  - CVE-2009-1955: XML bomb in web server module
  - CVE-2003-1564: Parsing library allows XML bomb
CWE-777: Regular Expression without Anchors

Description:
The product uses a regular expression to perform neutralization, but the regular expression is not anchored and may allow malicious or malformed data to slip through.

Extended Description:
When performing tasks such as validating against a set of allowed inputs (allowlist), data is examined and possibly modified to ensure that it is well-formed and adheres to a list of safe values. If the regular expression is not anchored, malicious or malformed data may be included before or after any string matching the regular expression. The type of malicious data that is allowed will depend on the context of the application and which anchors are omitted from the regular expression.

Affected languages: Not Language-Specific
Affected technologies: Not Technology-Specific
Parent weaknesses: CWE-625

Consequences:
  - Availability: Bypass Protection Mechanism

Mitigations:
  - [Implementation] Be sure to understand both what will be matched and what will not be matched by a regular expression. Anchoring the ends of the expression will allow the programmer to define an allowlist strictly limited to what is matched by the text in the regular expression. If you are using a package that only 

Demonstrative examples:
Consider a web application that supports multiple languages. It selects messages for an appropriate language by using the lang parameter.
The previous code attempts to match only alphanumeric values so that language values such as "english" and "french" are valid while also protecting against path traversal, CWE-22. However, the regular expression anchors are omitted, so any text containing at least one alphanumeric character will now pass the validation step. For example, the attack string below will match the regular expression.
$dir = "/home/cwe/languages"; $lang = $_GET['lang']; if (preg_match("/[A-Za-z0-9]+/", $lang)) { include("$dir/$lang"); } else { echo "You shall not pass!\n"; }
../../etc/passwd

This code uses a regular expression to validate an IP string prior to using it in a call to the "ping" command.
Since the regular expression does not have anchors (CWE-777), i.e. is unbounded without ^ or $ characters, then prepending a 0 or 0x to the beginning of the IP address will still result in a matched regex pattern. Since the ping command supports octal and hex prepended IP addresses, it will use the unexpectedly valid IP address (CWE-1389). For example, "0x63.63.63.63" would be considered equivalent to "99.63.63.63". As a result, the attacker could potentially ping systems that the attacker cannot reach directly.
import subprocess 
		  import re 
		   
		  def validate_ip_regex(ip: str): 
		   
		    ip_validator = re.compile(r"((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}") 
		    if

Real-world examples:
  - CVE-2022-30034: Chain: Web UI for a Python RPC framework does not use regex anchors to validate user login emails (CWE-777), potentially allowing bypass of OAuth (CWE-1390).
CWE-779: Logging of Excessive Data

Description:
The product logs too much information, making log files hard to process and possibly hindering recovery efforts or forensic analysis after an attack.

Extended Description:
While logging is a good practice in general, and very high levels of logging are appropriate for debugging stages of development, too much logging in a production environment might hinder a system administrator's ability to detect anomalous conditions. This can provide cover for an attacker while attempting to penetrate a system, clutter the audit trail for forensic analysis, or make it more difficult to debug problems in a production environment.

Affected languages: Not Language-Specific
Parent weaknesses: CWE-400

Consequences:
  - Availability: DoS: Resource Consumption (CPU)
  - Non-Repudiation: Hide Activities
  - Non-Repudiation: Hide Activities

Detection methods:
  - Automated Static Analysis: Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without havin

Mitigations:
  - [Architecture and Design] Suppress large numbers of duplicate log messages and replace them with periodic summaries. For example, syslog may include an entry that states "last message repeated X times" when recording repeated events.
  - [Architecture and Design] Support a maximum size for the log file that can be controlled by the administrator. If the maximum size is reached, the admin should be notified. Also, consider reducing functionality of the product. This may result in a denial-of-service to legitimate product users, but it will prevent the product
  - [Implementation] Adjust configurations appropriately when the product is transitioned from a debug state to production.

Real-world examples:
  - CVE-2007-0421: server records a large amount of data to the server log when it receives malformed headers
  - CVE-2002-1154: chain: application does not restrict access to front-end for updates, which allows attacker to fill the error log
CWE-780: Use of RSA Algorithm without OAEP

Description:
The product uses the RSA algorithm but does not incorporate Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption.

Extended Description:
Padding schemes are often used with cryptographic algorithms to make the plaintext less predictable and complicate attack efforts. The OAEP scheme is often used with RSA to nullify the impact of predictable common text.

Affected languages: Not Language-Specific
Parent weaknesses: CWE-327

Consequences:
  - Access Control: Bypass Protection Mechanism

Detection methods:
  - Automated Static Analysis: Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without havin

Demonstrative examples:
The example below attempts to build an RSA cipher.
While the previous code successfully creates an RSA cipher, the cipher does not use padding. The following code creates an RSA cipher using OAEP.
public Cipher getRSACipher() { Cipher rsa = null; try { rsa = javax.crypto.Cipher.getInstance("RSA/NONE/NoPadding"); } catch (java.security.NoSuchAlgorithmException e) { log("this should never happen", e); } catch (javax.crypto.NoSuchPaddingException e) { log("this should never happen", e); } return rsa; }
public Cipher getRSACipher() { Cipher rsa = null; try { rsa = javax.crypto.Cipher.getInstance("RSA/ECB/OAEPWithMD5AndMGF1Padding"); } catch (java.security.NoSuchAlgorithmException e) { log("this should never happen", e); } catch (javax.crypto.NoSuchPaddingException e) { log("this should never h
CWE-781: Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code

Description:
The product defines an IOCTL that uses METHOD_NEITHER for I/O, but it does not validate or incorrectly validates the addresses that are provided.

Extended Description:
When an IOCTL uses the METHOD_NEITHER option for I/O control, it is the responsibility of the IOCTL to validate the addresses that have been supplied to it. If validation is missing or incorrect, attackers can supply arbitrary memory addresses, leading to code execution or a denial of service.

Affected languages: C, C++
Parent weaknesses: CWE-1285

Consequences:
  - Integrity: Modify Memory

Mitigations:
  - [Implementation] If METHOD_NEITHER is required for the IOCTL, then ensure that all user-space addresses are properly validated before they are first accessed. The ProbeForRead and ProbeForWrite routines are available for this task. Also properly protect and manage the user-supplied buffers, since the I/O Manager doe
  - [Architecture and Design] If possible, avoid using METHOD_NEITHER in the IOCTL and select methods that effectively control the buffer size, such as METHOD_BUFFERED, METHOD_IN_DIRECT, or METHOD_OUT_DIRECT.
  - [Architecture and Design] If the IOCTL is part of a driver that is only intended to be accessed by trusted users, then use proper access control for the associated device or device namespace. See References.

Real-world examples:
  - CVE-2006-2373: Driver for file-sharing and messaging protocol allows attackers to execute arbitrary code.
  - CVE-2009-0686: Anti-virus product does not validate addresses, allowing attackers to gain SYSTEM privileges.
  - CVE-2009-0824: DVD software allows attackers to cause a crash.
  - CVE-2008-5724: Personal firewall allows attackers to gain SYSTEM privileges.
  - CVE-2007-5756: chain: device driver for packet-capturing software allows access to an unintended IOCTL with resultant array index error.
CWE-782: Exposed IOCTL with Insufficient Access Control

Description:
The product implements an IOCTL with functionality that should be restricted, but it does not properly enforce access control for the IOCTL.

Extended Description:
When an IOCTL contains privileged functionality and is exposed unnecessarily, attackers may be able to access this functionality by invoking the IOCTL. Even if the functionality is benign, if the programmer has assumed that the IOCTL would only be accessed by a trusted process, there may be little or no validation of the incoming data, exposing weaknesses that would never be reachable if the attacker cannot call the IOCTL directly. 
             The implementations of IOCTLs will differ between operating system types and versions, so the methods of attack and prevention may vary widely.

Affected languages: C, C++
Parent weaknesses: CWE-749

Consequences:
  - Integrity: Varies by Context

Mitigations:
  - [Architecture and Design] In Windows environments, use proper access control for the associated device or device namespace. See References.

Real-world examples:
  - CVE-2009-2208: Operating system does not enforce permissions on an IOCTL that can be used to modify network settings.
  - CVE-2008-3831: Device driver does not restrict ioctl calls to its direct rendering manager.
  - CVE-2008-3525: ioctl does not check for a required capability before processing certain requests.
  - CVE-2008-0322: Chain: insecure device permissions allows access to an IOCTL, allowing arbitrary memory to be overwritten.
  - CVE-2007-4277: Chain: anti-virus product uses weak permissions for a device, leading to resultant buffer overflow in an exposed IOCTL.
CWE-783: Operator Precedence Logic Error

Description:
The product uses an expression in which operator precedence causes incorrect logic to be used.

Extended Description:
While often just a bug, operator precedence logic errors can have serious consequences if they are used in security-critical code, such as making an authentication decision.

Affected languages: C, C++, Not Language-Specific
Parent weaknesses: CWE-670

Consequences:
  - Confidentiality: Varies by Context

Detection methods:
  - Automated Static Analysis: Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without havin

Mitigations:
  - [Implementation] Regularly wrap sub-expressions in parentheses, especially in security-critical code.

Demonstrative examples:
In the following example, the method validateUser makes a call to another method to authenticate a username and password for a user and returns a success or failure code.
However, the method that authenticates the username and password is called within an if statement with incorrect operator precedence logic. Because the comparison operator "==" has a higher precedence than the assignment operator "=", the comparison operator will be evaluated first and if the method returns FAIL then the comparison will be true, the return variable will be set to true and SUCCESS will be returned. This operator precedence logic error can be easily resolved by properly using parentheses within the expression of the if statement, as shown below.
#define FAIL 0 #define SUCCESS 1 
                      ... 
 

In this example, the method calculates the return on investment for an accounting/financial application. The return on investment is calculated by subtracting the initial investment costs from the current value and then dividing by the initial investment costs.
However, the return on investment calculation will not produce correct results because of the incorrect operator precedence logic in the equation. The divide operator has a higher precedence than the minus operator, therefore the equation will divide the initial investment costs by the initial investment costs which will only subtract one from the current value. Again this operator precedence logic error can be resolved by the correct use of parentheses within the equation, as shown below.
public double calculateReturnOnInvestment(d

Real-world examples:
  - CVE-2008-2516: Authentication module allows authentication bypass because it uses "(x = call(args) == SUCCESS)" instead of "((x = call(args)) == SUCCESS)".
  - CVE-2008-0599: Chain: Language interpreter calculates wrong buffer size (CWE-131) by using "size = ptr ? X : Y" instead of "size = (ptr ? X : Y)" expression.
  - CVE-2001-1155: Chain: product does not properly check the result of a reverse DNS lookup because of operator precedence (CWE-783), allowing bypass of DNS-based access restrictions.
CWE-784: Reliance on Cookies without Validation and Integrity Checking in a Security Decision

Description:
The product uses a protection mechanism that relies on the existence or values of a cookie, but it does not properly ensure that the cookie is valid for the associated user.

Extended Description:
Attackers can easily modify cookies, within the browser or by implementing the client-side code outside of the browser. Attackers can bypass protection mechanisms such as authorization and authentication by modifying the cookie to contain an expected value.

Affected languages: Not Language-Specific
Affected technologies: Web Based, Web Server
Parent weaknesses: CWE-807, CWE-565

Consequences:
  - Access Control: Bypass Protection Mechanism

Mitigations:
  - [Architecture and Design] Avoid using cookie data for a security-related decision.
  - [Implementation] Perform thorough input validation (i.e.: server side validation) on the cookie data if you're going to use it for a security related decision.
  - [Architecture and Design] Add integrity checks to detect tampering.
  - [Architecture and Design] Protect critical cookies from replay attacks, since cross-site scripting or other attacks may allow attackers to steal a strongly-encrypted cookie that also passes integrity checks. This mitigation applies to cookies that should only be valid during a single transaction or session. By enforcing time

Demonstrative examples:
The following code excerpt reads a value from a browser cookie to determine the role of the user.

Cookie[] cookies = request.getCookies(); for (int i =0; i< cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("role")) { userRole = c.getValue(); } }

The following code could be for a medical records application. It performs authentication by checking if a cookie has been set.
The programmer expects that the AuthenticateUser() check will always be applied, and the "authenticated" cookie will only be set when authentication succeeds. The programmer even diligently specifies a 2-hour expiration for the cookie.
$auth = $_COOKIES['authenticated']; if (! $auth) { if (AuthenticateUser($_POST['user'], $_POST['password']) == "success") { // save the cookie to send out in future responses setcookie("authenticated", "1", time()+60*60*2); } else { ShowLoginScreen(); die("\n"); } } DisplayMedicalHistory($_POST['patient_ID']);

Real-world examples:
  - CVE-2009-1549: Attacker can bypass authentication by setting a cookie to a specific value.
  - CVE-2009-1619: Attacker can bypass authentication and gain admin privileges by setting an "admin" cookie to 1.
  - CVE-2009-0864: Content management system allows admin privileges by setting a "login" cookie to "OK."
  - CVE-2008-5784: e-dating application allows admin privileges by setting the admin cookie to 1.
  - CVE-2008-6291: Web-based email list manager allows attackers to gain admin privileges by setting a login cookie to "admin."
CWE-785: Use of Path Manipulation Function without Maximum-sized Buffer

Description:
The product invokes a function for normalizing paths or file names, but it provides an output buffer that is smaller than the maximum possible size, such as PATH_MAX.

Extended Description:
Passing an inadequately-sized output buffer to a path manipulation function can result in a buffer overflow. Such functions include realpath(), readlink(), PathAppend(), and others.

Affected languages: C, C++
Parent weaknesses: CWE-676, CWE-120, CWE-20

Consequences:
  - Integrity: Modify Memory

Detection methods:
  - Automated Static Analysis: Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without havin

Mitigations:
  - [Implementation] Always specify output buffers large enough to handle the maximum-size possible result from path manipulation functions.

Demonstrative examples:
In this example the function creates a directory named "output\<name>" in the current directory and returns a heap-allocated copy of its name.
For most values of the current directory and the name parameter, this function will work properly. However, if the name parameter is particularly long, then the second call to PathAppend() could overflow the outputDirectoryName buffer, which is smaller than MAX_PATH bytes.
char *createOutputDirectory(char *name) { 
                         char outputDirectoryName[128]; if (getCurrentDirectory(128, outputDirectoryName) == 0) { return null; } if (!PathAppend(outputDirectoryName, "output")) { return null; } if (!PathAppend(outputDirectoryName, name)) { 
                               
                                  return null;
CWE-786: Access of Memory Location Before Start of Buffer

Description:
The product reads or writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer.

Extended Description:
This typically occurs when a pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used.

Affected languages: Memory-Unsafe, C, C++
Parent weaknesses: CWE-119, CWE-119, CWE-119

Consequences:
  - Confidentiality: Read Memory
  - Integrity: Modify Memory
  - Integrity: Modify Memory

Detection methods:
  - Fuzzing: Fuzz testing (fuzzing) is a powerful technique for generating large numbers of diverse inputs - either randomly or algorithmically - and dynamically invoking the code with those inputs. Even with rand
  - Automated Dynamic Analysis: Use tools that are integrated during
	     compilation to insert runtime error-checking mechanisms
	     related to memory safety errors, such as AddressSanitizer
	     (ASan) for C/C++ [REF-1518].

Demonstrative examples:
In the following C/C++ example, a utility function is used to trim trailing whitespace from a character string. The function copies the input string to a local character string and uses a while statement to remove the trailing whitespace by moving backward through the string and overwriting whitespace with a NUL character.
However, this function can cause a buffer underwrite if the input character string contains all whitespace. On some systems the while statement will move backwards past the beginning of a character string and will call the isspace() function on an address outside of the bounds of the local buffer.
char* trimTrailingWhitespace(char *strMessage, int length) { 
                         char *retMessage; char *message = malloc(sizeof(char)*(length+1)); 
                     

The following example asks a user for an offset into an array to select an item.
The programmer allows the user to specify which element in the list to select, however an attacker can provide an out-of-bounds offset, resulting in a buffer over-read (CWE-126).
int main (int argc, char **argv) { char *items[] = {"boat", "car", "truck", "train"}; int index = GetUntrustedOffset(); printf("You selected %s\n", items[index-1]); }

Real-world examples:
  - CVE-2002-2227: Unchecked length of SSLv2 challenge value leads to buffer underflow.
  - CVE-2007-4580: Buffer underflow from a small size value with a large buffer (length parameter inconsistency, CWE-130)
  - CVE-2007-1584: Buffer underflow from an all-whitespace string, which causes a counter to be decremented before the buffer while looking for a non-whitespace character.
  - CVE-2007-0886: Buffer underflow resultant from encoded data that triggers an integer overflow.
  - CVE-2006-6171: Product sets an incorrect buffer size limit, leading to "off-by-two" buffer underflow.
CWE-790: Improper Filtering of Special Elements

Description:
The product receives data from an upstream component, but does not filter or incorrectly filters special elements before sending it to a downstream component.

Affected languages: Not Language-Specific
Parent weaknesses: CWE-138

Consequences:
  - Integrity: Unexpected State

Demonstrative examples:
The following code takes untrusted input and uses a regular expression to filter "../" from the input. It then appends this result to the /home/user/ directory and attempts to read the file in the final resulting path.
Since the regular expression does not have the /g global match modifier, it only removes the first instance of "../" it comes across. So an input value such as:
my $Username = GetUntrustedInput(); $Username =~ s/\.\.\///; my $filename = "/home/user/" . $Username; ReadAndSendFile($filename);
../../../etc/passwd