Do not make any assumptions about the size of environment variables, as an adversary could have full control over the environment. Calculate the length of the strings yourself, and dynamically allocate memory for your copies \[[STR31-C. Guarantee that storage for strings has sufficient space for character data and the NULL terminator]\]. |
This non-compliant code example copies the string returned by getenv() into a fixed size buffer. This can result in a buffer overflow.
char copy[16];
char *temp = getenv("TEST_ENV");
if (temp != NULL) {
strcpy(copy, temp);
}
|
Use the strlen() function to calculate the size of the string and dynamically allocate the required space.
char *copy = NULL;
char *temp = getenv("TEST_ENV");
if (temp != NULL) {
copy = (char *)malloc(strlen(temp) + 1);
if (copy != NULL) {
strcpy(copy, temp);
}
else {
/* handle error condition */
}
}
|
Making assumptions about the size of an environmental variable could result in a buffer overflow attack.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
ENV01-A |
high |
likely |
low |
P27 |
L1 |
Compass/ROSE can detect violations of the rule by using the same method as STR31-C. Guarantee that storage for strings has sufficient space for character data and the null terminator.
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.4, "Communication with the environment" \[[Open Group 04|AA. C References#Open Group 04]\] Chapter 8, "Environment Variables" \[[Viega 03|AA. C References#Viega 03]\] Section 3.6, "Using Environment Variables Securely" |
ENV00-A. Do not store the pointer to the string returned by getenv() 10. Environment (ENV) ENV02-A. Beware of multiple environment variables with the same name