# VNX-193: Off-by-one Error

Reports C/C++ sizes and indices one off for the terminator or last element.

| Field | Value |
|---|---|
| Rule ID | `VNX-193` |
| Severity | Medium |
| SARIF level | `warning` |
| Kind | `sast` |
| Languages | C, C++ |
| CWE | [CWE-193](https://cwe.mitre.org/data/definitions/193.html) |
| CAPEC | [CAPEC-100](https://capec.mitre.org/data/definitions/100.html) |
| ATT&CK | [T1190](https://attack.mitre.org/techniques/T1190/) |
| CWSS vector | `CWSS:1.0/TI:M/AP:RU/AL:S/IC:N/FC:LT/RP:RU/RL:S/AV:L/AS:N/IN:A/SC:A/BI:M/DI:H/EX:M/EC:N/P:C` |
| Tags | `off-by-one` `arithmetic` `buffer` `cwe-193` |
| Source | [`internal/sast/rules/vnx-193.rego`](https://github.com/Vulnesis/cli/blob/main/internal/sast/rules/vnx-193.rego) |

## Overview

VNX-193 maps to [CWE-193: Off-by-one Error](https://cwe.mitre.org/data/definitions/193.html). C strings need one byte more than their length for the terminating NUL, and an array of N elements ends at index N - 1. Getting either wrong by one writes a byte past the buffer, which is enough to corrupt a neighbouring variable, a heap header or a saved frame pointer.

## What gets flagged

```c
char *out = malloc(strlen(name));      /* flagged: no room for '\0' */
strcpy(out, name);

char tmp[64];
tmp[sizeof(tmp)] = '\0';               /* flagged: one past the end */

static int slots[SLOTS];
for (i = 0; i <= SLOTS; i++)           /* flagged */
	slots[i] = 0;

strncat(path, user, sizeof(path));     /* flagged */
strncpy(buf_, text, strlen(text));     /* flagged: never terminated */
```

Not flagged: `strlen(s) + 1` allocations, `sizeof(x) - 1` bounds and indices, `strncat(d, s, sizeof(d) - strlen(d) - 1)`, a `malloc(strlen(s))` used for a length-prefixed copy with `memcpy` and no terminator, loops over arrays declared with a larger bound, strings and comments.

## Remediation

```c
char *out = malloc(strlen(name) + 1);
tmp[sizeof(tmp) - 1] = '\0';
for (i = 0; i < SLOTS; i++)
	slots[i] = 0;
strncat(path, user, sizeof(path) - strlen(path) - 1);
```

## References

- [CWE-193: Off-by-one Error](https://cwe.mitre.org/data/definitions/193.html)
- [SEI CERT STR31-C: Guarantee that storage for strings has sufficient space](https://wiki.sei.cmu.edu/confluence/display/c/STR31-C.+Guarantee+that+storage+for+strings+has+sufficient+space+for+character+data+and+the+null+terminator)

## Suppressing this rule

Put a `nosec` comment on the line, or on line 1 to cover the whole file. Use the comment marker of the file's language (`#`, `//`, `--` or `;`):

```text
# nosec vnx-193
// nosec vnx-193
```

Or record an ignore rule: `vulnetix ignore add --rule vnx-193 --reason "..."`. See [Suppressing findings](/sast/guides/suppressing-findings.md).
