Copying data to a buffer that is not large enough to hold that data results in a buffer overflow. While not limited to null-terminated byte strings (NTBS), buffer overflows often occur when manipulating NTBS datastrings. To prevent such errors, limit copies either through truncation or, preferably, ensure that the destination is of sufficient size to hold the character data to be copied and the null-termination character. (See recommendation STR03-C. Do not inadvertently truncate a string.)
...
Wiki Markup |
---|
Command-line arguments are passed to {{main()}} as pointers to null-terminated byte strings in the array members {{argv\[0\]}} through {{argv\[argc-1\]}}. If the value of {{argc}} is greater than zero, the string pointed to by {{argv\[0\]}} is, by convention, the program name. If the value of {{argc}} is greater than one, the strings referenced by {{argv\[1\]}} through {{argv\[argc-1\]}} are the actual program arguments. |
...
Remember to add a byte to accommodate the null-terminated byte null terminator in the string.
Compliant Solution (argv
) (strcpy_s()
)
...
Environmental variables are loaded into process memory when the program is loaded. As a result, the length of these null-terminated byte strings can be determined by calling the strlen()
function, and the resulting length can be used to allocate adequate dynamic memory:
...
Code Block | ||
---|---|---|
| ||
char* name; /* initialized externally */ char filename[128]; snprintf( filename, sizeof( filename), "%s.txt", name); /* open filename * / |
Risk Assessment
Copying NTBS data a string to a buffer that is too small to hold that data results in a buffer overflow. Attackers can exploit this condition to execute arbitrary code with the permissions of the vulnerable process.
...