CWE-135 Base Borrador

Incorrect Calculation of Multi-Byte String Length

This vulnerability occurs when software incorrectly measures the length of strings containing multi-byte or wide characters, leading to buffer overflows, data corruption, or crashes.

Definición

What is CWE-135?

This vulnerability occurs when software incorrectly measures the length of strings containing multi-byte or wide characters, leading to buffer overflows, data corruption, or crashes.
Many programming languages and systems use multi-byte character encodings (like UTF-8) or wide characters (like UTF-16) where a single logical character can be made of multiple bytes. Standard string length functions (like strlen in C) often count bytes, not characters, which creates a mismatch. When security checks or memory allocations rely on this incorrect count, buffers can be overrun or under-read, creating a critical entry point for attacks. Developers encounter this when handling international text, file paths, or user input without using encoding-aware functions. To prevent it, always use dedicated library functions designed for your specific character encoding (like mbstowcs or wcslen for wide strings) and validate that memory operations account for the maximum possible bytes per character, not just the count of logical units.
Impacto en el mundo real

Real-world CVEs caused by CWE-135

Todavía no hay CVEs públicos enlazados a esta CWE en el catálogo de MITRE.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    Identifica una ruta de código que maneje entrada no confiable sin validación.

  2. 2

    Crea un payload que ejercite el comportamiento inseguro — inyección, traversal, overflow o abuso de lógica.

  3. 3

    Envía el payload a través de una solicitud normal y observa la reacción de la aplicación.

  4. 4

    Itera hasta que la respuesta filtre datos, ejecute código del atacante o escale privilegios.

Ejemplo de código vulnerable

Vulnerable C

The following example would be exploitable if any of the commented incorrect malloc calls were used.

Vulnerable C
#include <stdio.h>
  #include <strings.h>
  #include <wchar.h>
  int main() {
  		wchar_t wideString[] = L"The spazzy orange tiger jumped " \
  		"over the tawny jaguar.";
  		wchar_t *newString;
  		printf("Strlen() output: %d\nWcslen() output: %d\n",
  		strlen(wideString), wcslen(wideString));
  		/* Wrong because the number of chars in a string isn't related to its length in bytes //
  		newString = (wchar_t *) malloc(strlen(wideString));
  		*/
  		/* Wrong because wide characters aren't 1 byte long! //
  		newString = (wchar_t *) malloc(wcslen(wideString));
  		*/
  		/* Wrong because wcslen does not include the terminating null */
  		newString = (wchar_t *) malloc(wcslen(wideString) * sizeof(wchar_t));
  		/* correct! */
  		newString = (wchar_t *) malloc((wcslen(wideString) + 1) * sizeof(wchar_t));
  		/* ... */
  }
Ejemplo de código seguro

Secure pseudo

Seguro pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
  const safe = validateAndEscape(input);
  return executeWithGuards(safe);
}
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Lista de prevención

How to prevent CWE-135

  • Implementation Always verify the length of the string unit character.
  • Implementation Use length computing functions (e.g. strlen, wcslen, etc.) appropriately with their equivalent type (e.g.: byte, wchar_t, etc.)
Señales de detección

How to detect CWE-135

Automated Static Analysis High

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 having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)

Auto-corrección de Plexicus

Plexicus detecta automáticamente CWE-135 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.

Preguntas frecuentes

Frequently asked questions

¿Qué es CWE-135?

This vulnerability occurs when software incorrectly measures the length of strings containing multi-byte or wide characters, leading to buffer overflows, data corruption, or crashes.

¿Qué gravedad tiene CWE-135?

MITRE no ha publicado una calificación de probabilidad de explotación para esta debilidad. Trátala como de impacto medio hasta que tu modelo de amenazas demuestre lo contrario.

¿Qué lenguajes o plataformas se ven afectados por CWE-135?

MITRE lists the following affected platforms: C, C++.

¿Cómo puedo prevenir CWE-135?

Always verify the length of the string unit character. Use length computing functions (e.g. strlen, wcslen, etc.) appropriately with their equivalent type (e.g.: byte, wchar_t, etc.)

¿Cómo detecta y corrige Plexicus CWE-135?

El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-135 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-135?

MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/135.html. También puedes consultar la documentación de OWASP y NIST para guías relacionadas.

Debilidades relacionadas

Weaknesses related to CWE-135

CWE-682 Padre

Incorrect Calculation

This vulnerability occurs when software performs a calculation that produces wrong or unexpected results, which are then used to make…

CWE-128 Hermano

Wrap-around Error

A wrap-around error happens when a variable exceeds the maximum value its data type can hold, causing it to unexpectedly reset to a very…

CWE-131 Hermano

Incorrect Calculation of Buffer Size

This vulnerability occurs when a program miscalculates the amount of memory needed for a buffer, potentially leading to a buffer overflow…

CWE-1335 Hermano

Incorrect Bitwise Shift of Integer

This vulnerability occurs when a program attempts to shift an integer's bits by an invalid amount—either a negative number or a value…

CWE-1339 Hermano

Insufficient Precision or Accuracy of a Real Number

This vulnerability occurs when a program uses a data type or algorithm that cannot accurately represent or calculate the fractional part…

CWE-190 Hermano

Integer Overflow or Wraparound

Integer overflow or wraparound occurs when a calculation produces a numeric result that exceeds the maximum value a variable can hold.…

CWE-191 Hermano

Integer Underflow (Wrap or Wraparound)

Integer underflow occurs when a subtraction operation results in a value smaller than the data type's minimum limit, causing the value to…

CWE-193 Hermano

Off-by-one Error

An off-by-one error occurs when a program incorrectly calculates a boundary, such as a loop counter or array index, by being one unit too…

CWE-369 Hermano

Divide By Zero

A divide-by-zero error occurs when software attempts to perform a division operation where the denominator is zero.

Listo cuando tú lo estés

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.