TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Signedness and Truncation Bugs (CWE-195, CWE-197)

Signedness and Truncation Bugs (CWE-195, CWE-197)

C converts between integer types silently. A signed int passed where a size_t is expected becomes unsigned; a 64-bit length stored in a 16-bit field loses its top bits. Both conversions are perfectly legal and both produce numbers that the programmer never meant. In memory-safety terms the two classic outcomes are: a negative length that passes a bounds check (because the check is signed) and then becomes an enormous unsigned length in memcpy; and a truncated size used for an allocation while the full size is used for the copy. Both look like correct code in review because every line, read alone, is correct.

Definitions

  • Signed-to-unsigned conversion (CWE-195): -1 converted to size_t is SIZE_MAX, 18,446,744,073,709,551,615 on 64-bit Linux.
  • Usual arithmetic conversions: in int < unsigned, the int is converted to unsigned first, so -1 < 1u is false. Casting the unsigned side to int "fixes" the warning and keeps the comparison signed, which is how the toy below goes wrong.
  • Truncation (CWE-197, Numeric Truncation Error): assigning to a narrower type keeps the low bits: (uint16_t)70004 == 4468.
  • Sign extension: converting a negative int8_t/char to a wider type copies the sign bit; (uint32_t)(int8_t)0x80 == 0xFFFFFF80. A byte from a packet stored in plain char (signed on x86) and used as an index or length goes wrong this way.

Bug 1: a negative length passes the check

field_len returns the length of the first ;-terminated field, or -1 if there is no ;. copy_field compares the length with the destination size, but in int, so -1 passes, and memcpy receives -1 as a size_t:

bash · try it yourself
cat > sign.c <<'SRC'
#include <stdio.h>
#include <string.h>

/* Returns the length of the field, or -1 if the message is malformed. */
static int field_len(const char *msg) {
    const char *end = strchr(msg, ';');
    return end ? (int)(end - msg) : -1;
}

static int copy_field(char *dst, size_t dstsz, const char *msg) {
    int len = field_len(msg);
    if (len >= (int)dstsz)            /* BUG: -1 passes this check */
        return -1;
    memcpy(dst, msg, len);            /* len converted to size_t: 18446744073709551615 */
    dst[len] = '\0';
    return 0;
}

int main(void) {
    setvbuf(stdout, NULL, _IONBF, 0);
    char name[16];
    if (copy_field(name, sizeof name, "alice;admin=no") == 0) printf("name = %s\n", name);
    copy_field(name, sizeof name, "no-terminator");
    return 0;
}
SRC
gcc -g -O0 -Wall -Wextra -Wsign-conversion sign.c -o sign 2>&1 | grep -E 'warning'
gcc -g -O0 -fsanitize=address sign.c -o sign-asan && ./sign-asan 2>&1 | grep -E '^name|ERROR|#1 |SUMMARY'
echo "exit code: ${PIPESTATUS[0]}"
sign.c:14:22: warning: conversion to ‘size_t’ {aka ‘long unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion]
name = alice
==21==ERROR: AddressSanitizer: negative-size-param: (size=-1)
    #1 0x57dbf0ca8335 in copy_field /home/learner/sign.c:14
SUMMARY: AddressSanitizer: negative-size-param ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors_memintrinsics.inc:115 in memcpy
exit code: 1

ASan has a dedicated report for this case, negative-size-param: (size=-1): a memcpy whose size, read as signed, is negative. Without ASan, memcpy would start copying 18 quintillion bytes and crash when it reaches unmapped memory, after overwriting everything above name on the stack. Note the warning: -Wall -Wextra alone are silent; only -Wsign-conversion flags line 14, the implicit int → size_t conversion at the memcpy. That warning is noisy in old code, which is why it isn't in -Wall, and valuable in new code.

Bug 2: a truncated size

The second toy builds a packet with a 4-byte header. The protocol's length field is 16 bits, so the developer computed the total in a uint16_t "to match". A payload of 70,000 bytes makes the total 70,004, which is stored as 70,004 − 65,536 = 4,468:

bash · try it yourself
cat > trunc.c <<'SRC'
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Builds a packet: 4-byte header + payload. Sizes are kept in 16-bit fields "like the protocol". */
static uint8_t *build(const uint8_t *payload, size_t plen) {
    uint16_t total = 4 + plen;                 /* BUG: truncated when plen > 65531 */
    uint8_t *pkt = malloc(total);
    memcpy(pkt, "HDR0", 4);
    memcpy(pkt + 4, payload, plen);            /* copies the full payload */
    printf("payload %zu -> packet buffer %u bytes\n", plen, total);
    return pkt;
}

int main(void) {
    setvbuf(stdout, NULL, _IONBF, 0);
    static uint8_t big[70000];
    free(build(big, 100));
    free(build(big, sizeof big));
    return 0;
}
SRC
gcc -g -O0 -Wall -Wconversion trunc.c -o trunc 2>&1 | grep -E 'warning'
gcc -g -O0 -fsanitize=address trunc.c -o trunc-asan && ./trunc-asan 2>&1 | grep -E '^payload|ERROR|WRITE|#1 |located'
echo "== clang's implicit-conversion check names the truncation itself"
clang -g -O0 -fsanitize=implicit-conversion trunc.c -o trunc-c && ./trunc-c 2>&1 | grep 'runtime error' | head -1
trunc.c:8:22: warning: conversion from ‘size_t’ {aka ‘long unsigned int’} to ‘uint16_t’ {aka ‘short unsigned int’} may change value [-Wconversion]
payload 100 -> packet buffer 104 bytes
==21==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x521000001274 at pc 0x7b3e40e0e303 bp 0x7ffe8fd74ed0 sp 0x7ffe8fd74678
WRITE of size 70000 at 0x521000001274 thread T0
    #1 0x62b180fe12cd in build /home/learner/trunc.c:11
0x521000001274 is located 0 bytes after 4468-byte region [0x521000000100,0x521000001274)
allocated by thread T0 here:
    #1 0x62b180fe1293 in build /home/learner/trunc.c:9
== clang's implicit-conversion check names the truncation itself
trunc.c:8:22: runtime error: implicit conversion from type 'size_t' (aka 'unsigned long') of value 70004 (64-bit, unsigned) to type 'uint16_t' (aka 'unsigned short') changed the value to 4468 (16-bit, unsigned)
  • -Wconversion warns at trunc.c:8:22: size_t to uint16_t "may change value".
  • ASan: WRITE of size 70000, 0 bytes after 4468-byte region, allocated at line 9: the 4,468-byte buffer from the truncated total, overflowed by the full payload copy at line 11.
  • Clang's -fsanitize=implicit-conversion reports the cause, not the effect: value 70004 … changed the value to 4468.

Root cause

Both bugs mix the type used for a check or allocation with a different type used for the copy. In bug 1 the error code -1 shares a variable with valid lengths, and the check is signed while memcpy is unsigned. In bug 2 the size of the memory buffer was confused with the size of a protocol field: a 16-bit field limits what the protocol can express, it doesn't make longer payloads impossible.

The fix

Keep lengths in size_t from the moment they are computed, keep error reporting separate from lengths, and check a protocol limit explicitly:

c · try it yourself
#include <stdint.h>
#include <stdio.h>
#include <string.h>

/* Length and status are separate: returns 0 and sets *len, or -1. */
static int field_len(const char *msg, size_t *len) {
    const char *end = strchr(msg, ';');
    if (!end) return -1;
    *len = (size_t)(end - msg);
    return 0;
}

static int copy_field(char *dst, size_t dstsz, const char *msg) {
    size_t len;
    if (field_len(msg, &len) != 0 || len >= dstsz) return -1;
    memcpy(dst, msg, len);
    dst[len] = '\0';
    return 0;
}

#define MAX_PACKET 65535u                 /* the 16-bit length field's limit */
static int packet_size(size_t plen, uint16_t *total) {
    if (plen > MAX_PACKET - 4) return -1; /* refuse, don't truncate */
    *total = (uint16_t)(4 + plen);
    return 0;
}

int main(void) {
    char name[16];
    const char *msgs[] = {"alice;admin=no", "no-terminator", "a-name-that-is-far-too-long;x"};
    for (int i = 0; i < 3; i++)
        printf("%-30s -> %s\n", msgs[i], copy_field(name, sizeof name, msgs[i]) == 0 ? name : "rejected");
    size_t sizes[] = {100, 65531, 65532, 70000};
    for (int i = 0; i < 4; i++) {
        uint16_t t;
        if (packet_size(sizes[i], &t) == 0) printf("payload %5zu -> packet %u\n", sizes[i], t);
        else printf("payload %5zu -> rejected (too large for the length field)\n", sizes[i]);
    }
    return 0;
}
alice;admin=no                 -> alice
no-terminator                  -> rejected
a-name-that-is-far-too-long;x  -> rejected
payload   100 -> packet 104
payload 65531 -> packet 65535
payload 65532 -> rejected (too large for the length field)
payload 70000 -> rejected (too large for the length field)

The boundary is tested on both sides: 65,531 + 4 = 65,535 fits the field, 65,532 doesn't.

How these bugs are detected

  • Warnings: -Wsign-compare (in -Wall for C++, -Wextra for C), -Wsign-conversion, -Wconversion. In new code, compile with them and treat them as errors; in old code, triage the ones that touch sizes and indexes first.
  • Sanitizers: ASan's negative-size-param; Clang's -fsanitize=implicit-conversion (truncation and sign changes) and -fsanitize=integer (all integer checks).
  • Review: look for functions returning int that are both a length and an error code, (int) casts that silence a comparison warning, plain char used for bytes, and every assignment of a size into a narrower field.

Pitfalls

  • Casting to silence a warning. len >= (int)dstsz silenced -Wsign-compare and created the bug; the right change was to make len unsigned.
  • ssize_t from read() is signed so it can return -1. Check for < 0 before using it as a length.
  • char for bytes: use unsigned char or uint8_t for binary data; char is signed on x86-64 Linux and unsigned on Arm Linux, so the same code behaves differently.

Practice

1. What is (size_t)-1 on 64-bit Linux, and why did ASan call it "negative"?

18,446,744,073,709,551,615 (2⁶⁴ − 1). ASan's interceptor reinterprets the size as signed and reports sizes with the top bit set as negative-size-param, because they almost always come from a negative int.

2. What does uint8_t b = 0x80; int i = (char)b; give on x86-64?

char is signed there, so (char)0x80 is −128, and i is −128. Used as an array index, that reads 128 bytes before the array.

3. Why is "store the total in a uint16_t because the protocol field is 16 bits" wrong?

The field limits what can be sent, not what the caller can pass. The limit must be checked, and too-large payloads rejected or split; storing in 16 bits only hides the size.

Test yourself

Why did len = -1 pass if (len >= (int)dstsz)?

  1. dstsz was 0
  2. The comparison is signed and -1 < 16, so the 'too long' branch isn't taken
  3. memcpy checks it
  4. -1 is unsigned

What did ASan report for memcpy with size -1?

  1. heap-buffer-overflow
  2. negative-size-param: (size=-1)
  3. stack-overflow
  4. Nothing

A 70,000-byte payload plus a 4-byte header stored in uint16_t becomes:

  1. 70004
  2. 65535
  3. 4468
  4. 0

Which warning flagged the implicit int-to-size_t conversion at the memcpy?

  1. -Wall
  2. -Wextra
  3. -Wsign-conversion
  4. -Wformat