Allocate sufficient space when copying a null-terminated byte string from a source to a destination array. Remember to allocate sufficient space to store the string contents as well as the null-termination character.
Non-Compliant Code Example
...
Wiki Markup |
---|
Command line arguments are read from the command line and stored in process memory. Command line arguments are passed to {{main()}} as argumentspointers to null-terminated byte strings in the array members {{argv\[0\]}} through {{argv\[argc-1\]}}. |
Code Block |
---|
int main(int argc, char *argv[]) { /* ... */ } |
Wiki Markup |
---|
If the value of {{argc}} is greater than zero, the string pointed to by {{argv\[0\]}} represents the program name. If the value of {{argc}} is greater than one, the strings pointed to by {{argv\[1\]}} through {{argv\[argc-1\]}} represent the program parameters. In the following definition for {{main()}} the array members {{argv\[0\]}} through {{argv\[argc-1\]}} inclusive contain pointers to null-terminated byte strings. |
...
Wiki Markup |
---|
If the value of {{argc}} is greater than zero, the string pointed to by {{argv\[0\]}} represents the program name. If the value of argc is greater than one, the strings pointed to by {{argv\[1\]}} through {{argv\[argc-1\]}} represent the program parameters. |
The getenv()
function searches an environment list, provided by the host environment, for a string that matches the string pointed to by name. The set of environment names and the method for altering the environment list are implementation-defined.
Non-Compliant Code Example
Wiki Markup |
---|
The contents of {{argv\[0\]}} can be manipulated by an attacker to cause a buffer overflow in the following program: |
...
Non-Compliant Code Example
Reading environment variables The getenv()
function searches an environment list, provided by the host environment, for a string that matches the string pointed to by name. The set of environment names and the method for altering the environment list are implementation-defined. Environment variables can be arbitrarily large, and copying them into fixed length arrays can also without first determining the size and allocating adequate storage can result in a buffer overflow.
Code Block |
---|
char buff[256]; strcpy(buff, (char *)getenv("EDITOR")); |
Compliant Solution
Environmental variables are loaded into process memory when the program is loaded. Resultantly, these null-terminated byte strings have a fixed length. The strlen()
function should be used to determine the length of environmental variables so that adequate memory can be dynamically allocated:
...