...
Because strtok()
modifies its argument, the string is subsequently unsafe and cannot be used in its original form. If you need to preserve the original string, copy it into a buffer and pass the address of the buffer to strtok()
instead of the original string.
...
Noncompliant Code Example
In this example, the strtok()
function is used to parse the first argument into colon-delimited tokens; it outputs each word from the string on a new line. Assume that PATH
is "/usr/bin:/usr/sbin:/sbin"
.
...
After the loop ends, path
is modified as follows: "/usr/bin\0/bin\0/usr/sbin\0/sbin\0"
. This is an issue because the local path
variable becomes /usr/bin
and because the environment variable PATH
has been unintentionally changed, which can have unintended consequences.
Compliant Solution
In this solution the string being tokenized is copied into a temporary buffer which is not referenced after the calls to strtok()
:
...
Another possibility is to provide your own implementation of strtok()
that does not modify the initial arguments.
Risk Assessment
Wiki Markup |
---|
To quote the Linux Programmer's Manual (man) page on {{strtok(3)}} \[[Linux 07|AA. C References#Linux 07]\]: |
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
STR06-A C | medium | likely | medium | P12 | L1 |
Automated Detection
Fortify SCA Version 5.0 is able to can detect violations of this recommendation.
Compass/ROSE can detect violations of this recommendation.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.21.5.8, "The {{strtok}} function" \[[Linux 07|AA. C References#Linux 07]\] [strtok(3)|http://www.kernel.org/doc/man-pages/online/pages/man3/strtok.3.html] |
...
07. Characters and Strings (STR) STR07-AC. Use TR 24731 for remediation of existing string manipulation code