...
Consequently, if the string returned by getenv()
needs to be altered, a local copy should be created to ensure that the environment is not directly and unintentionally modified. Altering the string returned by getenv()
results in undefined behavior.
Wiki Markup |
---|
Similarly, C99 \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] defines {{setlocale}} and {{localeconv}} as follows: |
...
Code Block | ||
---|---|---|
| ||
void strtrtrstr(char *str, char orig, char rep) { while (*str != '\0') { if (*str == orig) { *str = rep; } str++; } } /* ... */ char *env = getenv("TEST_ENV"); if (env == NULL) { /* Handle error */ } strtrtrstr(env,'"', '_'); /* ... */ |
...
Code Block | ||
---|---|---|
| ||
const char *env; char *copy_of_env; env = getenv("TEST_ENV"); if (env == NULL) { /* Handle error */ } copy_of_env = (char *)malloc(strlen(env) + 1); if (copy_of_env == NULL) { /* Handle error */ } strcpy(copy_of_env, env); strtrtrstr(copy_of_env,'\"', '_'); |
Compliant Solution (Modifying the Environment in POSIX)
...
Code Block | ||
---|---|---|
| ||
const char *env; char *copy_of_env; env = getenv("TEST_ENV"); if (env == NULL) { /* Handle error */ } copy_of_env = strdup(env); if (copy_of_env == NULL) { /* Handle error */ } strtrtrstr(copy_of_env,'\"', '_'); if (setenv("TEST_ENV", copy_of_env, 1) != 0) { /* Handle error */ } |
...
Code Block | ||
---|---|---|
| ||
const char *locale; char *copy_of_locale; locale = setlocale(LC_ALL, ""); if (locale == NULL) { /* Handle error */ } copy_of_locale = (char *)malloc(strlen(locale) + 1); if (copy_of_locale == NULL) { /* Handle error */ } strcpy(copy_of_locale, locale); terminate_on_dot(copy_of_locale); /* ... */ |
Risk Assessment
The Depending on the implementation, modifying the object pointed to by the return value of these functions causes undefined behavior. Even if the modification succeeds, the modified object may be overwritten by a subsequent call to the getenv()
, setlocale()
, localeconv()
, or localeconvstrerror()
functions. Depending on the implementation, modifying the object pointed to by the return value of these functions causes undefined behavior
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
ENV30-C | low | probable | medium | P4 | L3 |
...