Insecure API: atoi, atol, atof
Description
The atoi(), atol(), atof(), and similar functions don't handle errors. They don't check for integer overflow and can return a negative value. They have undefined behavior if the value of the result cannot be represented. They return 0 (or 0.0) if the string does not represent an integer (or decimal), which is indistinguishable from a correctly formatted, zero-denoting input string.
Examples
Insecure Code
c
int x = atoi(user_input);Secure Code
c
char *endptr; int x = strtol(user_input, &endptr, 10); if (endptr == user_input) { /* handle error */ }Remediation
Use strtol(), strtoll(), or strtod() instead, which allow for error checking and handling.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0806 |
| Category | Generic |
| Severity | MEDIUM |
| CWE | CWE-196 |
| Confidence | HIGH |
| Impact | MEDIUM |
| Likelihood | MEDIUM |
| Exploitability | MODERATE |
| Tags | error-handling, integer-overflow |
| OWASP | N/A |
References
- https://wiki.sei.cmu.edu/confluence/display/c/ERR34-C.+Detect+errors+when+converting+a+string+to+a+number
- https://rules.sonarsource.com/c/type/Bug/RSPEC-989