CWE-193 Base Borrador

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 high or too low. This often leads to buffer overflows,…

Definición

What is CWE-193?

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 high or too low. This often leads to buffer overflows, memory corruption, or unexpected program behavior.
This common programming mistake typically happens when developers use incorrect comparison operators (like <= instead of <) or miscalculate loop termination conditions. It's especially prevalent when dealing with zero-based indexing in arrays, strings, or memory buffers, where the boundary between the last valid element and the first invalid one is easy to misjudge. To prevent off-by-one errors, carefully review all loop conditions and boundary checks, paying close attention to whether your logic uses inclusive or exclusive upper limits. Using standardized container iteration methods (like iterators in C++ or for-each loops in other languages) instead of manual index calculations can eliminate many of these errors entirely.
Impacto en el mundo real

Real-world CVEs caused by CWE-193

  • Off-by-one error allows remote attackers to cause a denial of service and possibly execute arbitrary code via requests that do not contain newlines.

  • Off-by-one vulnerability in driver allows users to modify kernel memory.

  • Off-by-one error allows local users or remote malicious servers to gain privileges.

  • Off-by-one buffer overflow in function usd by server allows local users to execute arbitrary code as the server user via .htaccess files with long entries.

  • Off-by-one buffer overflow in version control system allows local users to execute arbitrary code.

  • Off-by-one error in FTP server allows a remote attacker to cause a denial of service (crash) via a long PORT command.

  • Off-by-one buffer overflow in FTP server allows local users to gain privileges via a 1024 byte RETR command.

  • Multiple buffer overflows in chat client allow remote attackers to cause a denial of service and possibly execute arbitrary code.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget.

  2. 2

    However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough space to contain the specified number of widgets, but it does not include the space for the NULL pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption.

  3. 3

    In this example, the code does not account for the terminating null character, and it writes one byte beyond the end of the buffer.

  4. 4

    The first call to strncat() appends up to 20 characters plus a terminating null character to fullname[]. There is plenty of allocated space for this, and there is no weakness associated with this first call. However, the second call to strncat() potentially appends another 20 characters. The code does not account for the terminating null character that is automatically added by strncat(). This terminating null character would be written one byte beyond the end of the fullname[] buffer. Therefore an off-by-one error exists with the second strncat() call, as the third argument should be 19.

  5. 5

    When using a function like strncat() one must leave a free byte at the end of the buffer for a terminating null character, thus avoiding the off-by-one weakness. Additionally, the last argument to strncat() is the number of characters to append, which must be less than the remaining space in the buffer. Be careful not to just use the total size of the buffer.

Ejemplo de código vulnerable

Vulnerable C

The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget.

Vulnerable C
int i;
  unsigned int numWidgets;
  Widget **WidgetList;
  numWidgets = GetUntrustedSizeValue();
  if ((numWidgets == 0) || (numWidgets > MAX_NUM_WIDGETS)) {
  	ExitError("Incorrect number of widgets requested!");
  }
  WidgetList = (Widget **)malloc(numWidgets * sizeof(Widget *));
  printf("WidgetList ptr=%p\n", WidgetList);
  for(i=0; i<numWidgets; i++) {
  	WidgetList[i] = InitializeWidget();
  }
  WidgetList[numWidgets] = NULL;
  showWidgets(WidgetList);
Ejemplo de código seguro

Secure C

When using a function like strncat() one must leave a free byte at the end of the buffer for a terminating null character, thus avoiding the off-by-one weakness. Additionally, the last argument to strncat() is the number of characters to append, which must be less than the remaining space in the buffer. Be careful not to just use the total size of the buffer.

Seguro C
char firstname[20];
  char lastname[20];
  char fullname[40];
  fullname[0] = '\0';
  strncat(fullname, firstname, sizeof(fullname)-strlen(fullname)-1);
  strncat(fullname, lastname, sizeof(fullname)-strlen(fullname)-1);
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-193

  • Implementation When copying character arrays or using character manipulation methods, the correct size parameter must be used to account for the null terminator that needs to be added at the end of the array. Some examples of functions susceptible to this weakness in C include strcpy(), strncpy(), strcat(), strncat(), printf(), sprintf(), scanf() and sscanf().
Señales de detección

How to detect CWE-193

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.)

CWE-193

Don't catalog this weakness. Prove it's reachable.

Plexicus turns CWE catalogs into evidence: every CWE-pattern is matched against your real code graph, reach is proven on a sandbox clone, and verified findings ship as reviewed PRs.

Preguntas frecuentes

Frequently asked questions

¿Qué es CWE-193?

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 high or too low. This often leads to buffer overflows, memory corruption, or unexpected program behavior.

¿Qué gravedad tiene CWE-193?

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-193?

MITRE lists the following affected platforms: C.

¿Cómo puedo prevenir CWE-193?

When copying character arrays or using character manipulation methods, the correct size parameter must be used to account for the null terminator that needs to be added at the end of the array. Some examples of functions susceptible to this weakness in C include strcpy(), strncpy(), strcat(), strncat(), printf(), sprintf(), scanf() and sscanf().

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

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

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

Debilidades relacionadas

Weaknesses related to CWE-193

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-135 Hermano

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…

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-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 para validar lo que importa?

Listo para validar lo que importa.

Plexicus es Proof-Driven AppSec: hallazgos validados, comprensión contextual y remediación revisada — anclada en evidencia, acotada contigo.

Calificación

Comprueba si el AI Swarm Pentest encaja en tu entorno.

Déjanos el contexto mínimo. Revisaremos el alcance y te indicaremos el siguiente paso comercial.

Antes de enviar — verifica que encajas

0 / 280

Sin compromiso. Si no encajas, te lo decimos.

SAMPLE HANDOVER · ILLUSTRATIVE

Sample evidence handover

A trimmed view of what your team receives at the end of an AI Swarm Pentest engagement. Real engagements include full technical evidence, executive narrative, and a remediation plan.

VALIDATED FINDING Evidence attached

Server-Side Request Forgery in webhooks/receiver

demo-project/sample-app · src/webhooks/receiver.py:42

SeverityHigh CVSS 3.18.6 Priority79 Confirmedvia replay

Untrusted caller-supplied URLs reach an internal egress without an allowlist. Replayed in a sandbox against a fresh authorized target — the same control was validated to fail twice.

REVIEWER-READY REMEDIATION Merge-ready PR

Validate the target URL against an allowlist of permitted hostnames. Reject private/internal IP ranges. Enforce HTTPS only.

plexicus/remediation/webhooks-ssrf 3 changed · 0 new files
42resp = requests.get(target_url)
42+if not is_allowed_host(target_url):
43+  raise WebhookRejected(target_url)
44+resp = requests.get(target_url, timeout=5)
Every engagement hands over:
  • Executive briefing
  • Validated findings list
  • Merge-ready PRs
  • Compliance mapping (NIS2 · DORA · CRA)
Ronda privada Para inversores