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. There is nothing you can do to avoid the race conditions inherent here, but you can limit your exposure.
Non-Compliant Coding Example
This non-compliant code example copies into a buffer of fixed size. This can result in a buffer overflow.
char *temp; char copy[16]; temp = getenv("TEST_ENV"); if(temp != NULL) strcpy(buff, temp);
Compliant Solution
Use strlen
to calculate size and dynamically allocate space.
char *temp; char *copy; if ((temp = getenv("TEST_ENV")) != NULL) { copy = malloc(strlen(temp) + 1); if (copy != NULL) { strcpy(copy, temp); } else { /* handle error condition */ } } else { return -1; }
Risk Assessment
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
ENV00-A |
1 (low) |
1 (unlikely) |
3 (low) |
P3 |
L3 |
References
[[ISO/IEC 9899-1999:TC2]] Section 7.20.4, "Communication with the environment"
[[Open Group 04]] Chapter 8, "Environment Variables"
[[Viega 03]] Section 3.6, "Using Environment Variables Securely"