User-Controlled Buffer Length

User-controlled buffer length

Description

Using user input as the length for copying, reading, or formatting can exceed the destination buffer's capacity.

Potential impact

  • Buffer overflows, denial of service, or memory corruption

Remediation

Limit the length to the destination buffer's capacity and use only validated sizes.

Examples

Before

c
size_t n = atoi(argv[1]);
memcpy(dst, src, n);

After

c
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>

int copy_input(char *dst, size_t dst_capacity,
               const char *src, size_t src_length,
               const char *raw_length) {
    char *end = NULL;
    errno = 0;
    uintmax_t parsed = strtoumax(raw_length, &end, 10);
    if (errno == ERANGE || end == raw_length || *end != '\0' ||
        parsed > SIZE_MAX || parsed > dst_capacity || parsed > src_length) {
        return -1;
    }

    memcpy(dst, src, (size_t)parsed);
    return 0;
}

Explanation:

  • Before: External input directly controls the copy length.
  • After: Have the caller supply the actual destination capacity and source length rather than using sizeof on a pointer. Validate numeric conversion, then pass only lengths within both buffers' bounds to memcpy.

References