This weakness can often be detected using automated static analysis tools. Many modern tools use data flow analysis or constraint-based techniques to minimize the number of false positives. Automated static analysis generally does not account for environmental considerations when reporting out-of-bounds memory operations. This can make it difficult for users to determine which warnings should be investigated first. For example, an analysis tool might report array index errors that originate from command line arguments in a program that is not expected to run with setuid or other special privileges.
Improper Validation of Array Index
This vulnerability occurs when software uses unverified, external input to calculate or access an array index, without properly checking that the index points to a valid location within the array's…
What is CWE-129?
Real-world CVEs caused by CWE-129
-
large ID in packet used as array index
-
negative array index as argument to POP LIST command
-
Integer signedness error leads to negative array index
-
product does not properly track a count and a maximum number, which can lead to resultant array index overflow.
-
Chain: device driver for packet-capturing software allows access to an unintended IOCTL with resultant array index error.
-
Chain: array index error (CWE-129) leads to deadlock (CWE-833)
Ruta del atacante paso a paso
- 1
In the code snippet below, an untrusted integer value is used to reference an object in an array.
- 2
If index is outside of the range of the array, this may result in an ArrayIndexOutOfBounds Exception being raised.
- 3
The following example takes a user-supplied value to allocate an array of objects and then operates on the array.
- 4
This example attempts to build a list from a user-specified value, and even checks to ensure a non-negative value is supplied. If, however, a 0 value is provided, the code will build an array of size 0 and then try to store a new Widget in the first location, causing an exception to be thrown.
- 5
In the following code, the method retrieves a value from an array at a specific array index location that is given as an input parameter to the method
Vulnerable Java
In the code snippet below, an untrusted integer value is used to reference an object in an array.
public String getValue(int index) {
return array[index];
} Secure C
However, this method only verifies that the given array index is less than the maximum length of the array but does not check for the minimum value (CWE-839). This will allow a negative value to be accepted as the input array index, which will result in reading data before the beginning of the buffer (CWE-127) and may allow access to sensitive memory. The input array index should be checked to verify that is within the maximum and minimum range required for the array (CWE-129). In this example the if statement should be modified to include a minimum range check, as shown below.
...
```
// check that the array index is within the correct*
*// range of values for the array*
if (index >= 0 && index < len) {
... How to prevent CWE-129
- Architecture and Design Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
- Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
- Requirements Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, Ada allows the programmer to constrain the values of a variable and languages such as Java and Ruby will allow the programmer to handle exceptions when an out-of-bounds index is accessed.
- Operation / Build and Compilation Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
- Operation Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
- Implementation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. When accessing a user-controlled array index, use a stringent range of values that are within the target array. Make sure that you do not allow negative values to be used. That is, verify the minimum as well as the maximum of the range of acceptable values.
- Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
- Architecture and Design / Operation Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.
How to detect CWE-129
This weakness can be detected using dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results.
Black box methods might not get the needed code coverage within limited time constraints, and a dynamic test might not produce any noticeable side effects even if it is successful.
Plexicus detecta automáticamente CWE-129 y abre un PR de corrección en menos de 60 segundos.
Codex Remedium escanea cada commit, identifica esta debilidad concreta y entrega un pull request listo para revisión con el parche. Sin tickets. Sin traspasos.
Frequently asked questions
¿Qué es CWE-129?
This vulnerability occurs when software uses unverified, external input to calculate or access an array index, without properly checking that the index points to a valid location within the array's bounds.
¿Qué gravedad tiene CWE-129?
MITRE califica la probabilidad de explotación como Alta — esta debilidad se explota activamente en la práctica y debe priorizarse para su remediación.
¿Qué lenguajes o plataformas se ven afectados por CWE-129?
MITRE lists the following affected platforms: C, C++.
¿Cómo puedo prevenir CWE-129?
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have…
¿Cómo detecta y corrige Plexicus CWE-129?
El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-129 en cada commit. Cuando hay coincidencia, nuestro agente Codex Remedium abre un PR de corrección con el código corregido, las pruebas y un resumen de una línea para el revisor.
¿Dónde puedo aprender más sobre CWE-129?
MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/129.html. También puedes consultar la documentación de OWASP y NIST para guías relacionadas.
Weaknesses related to CWE-129
Improper Validation of Specified Index, Position, or Offset in Input
This vulnerability occurs when software accepts user input to determine a location—like an array index, file position, or memory…
Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code
This vulnerability occurs when a Windows driver defines an IOCTL using METHOD_NEITHER but fails to properly check the user-supplied memory…
Improper Restriction of Operations within the Bounds of a Memory Buffer
This vulnerability occurs when software accesses a memory buffer but reads from or writes to a location outside its allocated boundary.…
Use of Out-of-range Pointer Offset
This vulnerability occurs when a program calculates a new memory address using a valid pointer and an offset, but the resulting address…
Memory Allocation with Excessive Size Value
This vulnerability occurs when a program allocates memory based on a user-supplied or untrusted size value without proper validation. If…
Further reading
- MITRE — CWE-129 oficial https://cwe.mitre.org/data/definitions/129.html
- Writing Secure Code https://www.microsoftpressstore.com/store/writing-secure-code-9780735617223
- Top 25 Series - Rank 14 - Improper Validation of Array Index https://web.archive.org/web/20100316064026/http://blogs.sans.org/appsecstreetfighter/2010/03/12/top-25-series-rank-14-improper-validation-of-array-index/
- Address Space Layout Randomization in Windows Vista https://learn.microsoft.com/en-us/archive/blogs/michael_howard/address-space-layout-randomization-in-windows-vista
- PaX https://en.wikipedia.org/wiki/Executable_space_protection#PaX
- Understanding DEP as a mitigation technology part 1 https://msrc.microsoft.com/blog/2009/06/understanding-dep-as-a-mitigation-technology-part-1/
- Least Privilege https://web.archive.org/web/20211209014121/https://www.cisa.gov/uscert/bsi/articles/knowledge/principles/least-privilege
Deja de pagar por desarrollador.
Empieza a cerrar el bucle.
Plexicus es el ASPM nativo de IA que escanea, filtra, corrige, pentestea y explica — de forma autónoma. Desarrolladores ilimitados, repos ilimitados, acciones de IA de uso justo. Nivel gratuito real, €269/mo anual cuando estés listo.