...
These range tests do nothing if the smaller type happens to have the same size and representation on a particular compiler.
...
Noncompliant Code Example
This non-compliant noncompliant code example converts the string token stored in the static array buff to a signed integer value using the atoi() function.
...
- do not need to set
errnoon an error - have undefined behavior if the value of the result cannot be represented
- return 0 if the string does not represent an integer, which is indistinguishable from a correctly formatted, zero-denoting input string.
...
Noncompliant Example
This non-compliant noncompliant example uses the sscanf() function to convert a string token to an integer. The sscanf() function has the same limitations as atoi().
...
The sscanf() function does return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure. However, sscanf() fails to report the other errors reported by strtol(), such as overflow.
Compliant Solution
The strtol(), strtoll(), strtoul(), and strtoull() functions convert a null-terminated byte string to long int, long long int, unsigned long int, and unsigned long long int representation, respectively.
...
| Code Block | ||
|---|---|---|
| ||
long sl;
int si;
char *end_ptr;
if (argc > 1) {
errno = 0;
sl = strtol(argv[1], &end_ptr, 10);
if ((sl == LONG_MIN)
|| (sl == LONG_MAX)
|| (end_ptr == argv[1]))
{
if (errno != 0) {
perror("strtol error");
}
else {
if (puts("error encountered during conversion") == EOF) {
/* Handle Error */
}
}
}
else if (sl > INT_MAX) {
printf("%ld too large!\n", sl);
}
else if (sl < INT_MIN) {
printf("%ld too small!\n", sl);
}
else if ('\0' != *end_ptr) {
if (puts("extra characters on input line\n") == EOF) {
/* Handle Error */
}
}
else {
si = (int)sl;
}
}
|
Risk Assessment
While it is relatively rare for a violation of this rule to result in a security vulnerability, it can easily result in lost or misinterpreted data.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
INT06-A C | medium | probable | medium | P8 | L2 |
Automated Detection
Fortify SCA Version 5.0 with the CERT C Rule Pack can detect violations of this recommendation.
...
atoi()scanf(),fscanf(),sscanf()- others?
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
| Wiki Markup |
|---|
\[[Klein 02|AA. C References#Klein 02]\]
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.1.4, "The {{strtol}}, {{strtoll}}, {{strtoul}}, and {{strtoull}} functions," Section 7.20.1.2, "The {{atoi}}, {{atol}}, and {{atoll}} functions," and Section 7.19.6.7, "The {{sscanf}} function" |
...
04. Integers (INT) INT07-A. Use only explicitly signed or unsigned char type for numeric values