buffer-overflow
Untrusted input used as the length of a copy.
- Group
- Code
- Runs
- Runs under ur scan:
ur scan --rule buffer-overflow - Level
- warning
- Reads
- Every file
- Fix
- None: the safe form depends on what the value is meant to be
Why
A value from outside the program, such as an environment variable, is the number of bytes memcpy or a function like it writes, so whoever chose it can write past the end of the buffer. Check the length against the size of the buffer it writes before the copy.
The fix, as Ur suggests it: check the length against the buffer's size.
For agents
Never copy as many bytes as input says; check the length against the destination's size first.
Example
src/name.cpp#include <cstdlib>
#include <cstring>
void copy_name(char* out, const char* name) {
const char* size = std::getenv("NAME_SIZE");
std::memcpy(out, name, std::strtoul(size, nullptr, 10));
}
$ ur scan --rule buffer-overflow
warning[buffer-overflow]: `std::getenv`, an environment variable, reaches `std::memcpy`
--> ./src/name.cpp:6:3 function `copy_name`
= step 1: ./src/name.cpp:5:22 `std::getenv`, an environment variable,
= step 2: ./src/name.cpp:6:26 passed to `std::strtoul`
= hint: check the length against the buffer's size
= see: ARR38-C. Guarantee that library functions do not form invalid pointers, SEI CERT C Coding Standard (2023-10-25), https://wiki.sei.cmu.edu/confluence/display/c/ARR38-C.+Guarantee+that+library+functions+do+not+form+invalid+pointers
scanned 1 file (no framework recognized)
buffer-overflow: 1 high, 0 medium
1 finding and 0 of medium confidence
Source
ARR38-C. Guarantee that library functions do not form invalid pointers, SEI CERT C Coding Standard (2023-10-25).