VNX-135: Incorrect Calculation of Multi-Byte String Length
Reports C/C++ code that confuses wide-character counts with byte counts: allocations and memcpy lengths taken from wcslen() without sizeof(wchar_t), wide-character APIs given sizeof(buf), and strlen() on a wchar_t string.
| Field | Value |
|---|---|
| Rule ID | VNX-135 |
| Severity | Medium |
| SARIF level | warning |
| Kind | sast |
| Languages | C, C++ |
| CWE | CWE-135 |
| CAPEC | CAPEC-66 |
| ATT&CK | 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 | multibyte unicode wchar cwe-135 |
| Source | internal/sast/rules/vnx-135.rego |
Overview
VNX-135 maps to CWE-135: Incorrect Calculation of Multi-Byte String Length. It reports:
malloc/xmalloc/alloca/reallocsized bywcslen()with nosizeof(and no* 2/* 4): one byte per wide character, or too few bytes for awcstombs()result.memcpy/memmove/memcmp/memsetgiven awcslen()count with nosizeof, which copies only part of the string.- A function that counts in wide characters (
wcsncpy,wcsncat,wcslcpy,wmemcpy,wmemset,swprintf,mbstowcs,fgetws,MultiByteToWideChar,GetWindowTextW, …) givensizeof(buf), a byte count two to four times the buffer’s length in characters. strlen()on a variable declaredwchar_t/WCHAR, usually through a(char *)cast.
What Gets Flagged
wchar_t *dst = malloc(wcslen(src) + 1); // FLAGGED: bytes, not wide chars
wchar_t buf[64];
wcsncpy(buf, who, sizeof(buf)); // FLAGGED: 256 counted as chars
memmove(dst, src, wcslen(src)); // FLAGGED
return strlen((const char *)title); // FLAGGED: title is wchar_t *
What Is Not Flagged
- Sizes multiplied by
sizeof(wchar_t)orsizeof(*p). - Counts written
sizeof(buf) / sizeof(buf[0]),ARRAY_SIZE()or_countof(). new wchar_t[wcslen(s) + 1](an element count), and narrow strings.- UTF-8 length mistakes in other languages (out of scope).
Remediation
Multiply wide-character counts by sizeof(wchar_t) when a byte count is needed, pass element counts (_countof(buf)) to wide-character APIs, and use wcslen() for wide strings.
References
- CWE-135: Incorrect Calculation of Multi-Byte String Length
- SEI CERT STR38-C: Do not confuse narrow and wide character strings and functions
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 ;):
# nosec vnx-135
// nosec vnx-135
Or record an ignore rule: vulnetix ignore add --rule vnx-135 --reason "...". See Suppressing findings.