...
If len
is equal to sizeof(buf)
, the null terminator is written 1 byte past the end of buf
.:
Code Block | ||||
---|---|---|---|---|
| ||||
char buf[1024]; ssize_t len = readlink("/usr/bin/perl", buf, sizeof(buf)); buf[len] = '\0'; |
An incorrect solution to this problem is to try to make buf
large enough that it can always hold the result.:
Code Block | ||||
---|---|---|---|---|
| ||||
long symlink_max; size_t bufsize; char *buf; ssize_t len; errno = 0; symlink_max = pathconf("/usr/bin/", _PC_SYMLINK_MAX); if (symlink_max == -1) { if (errno != 0) { /* handle error condition */ } bufsize = 10000; } else { bufsize = symlink_max+1; } buf = (char *)malloc(bufsize); if (buf == NULL) { /* handle error condition */ } len = readlink("/usr/bin/perl", buf, bufsize); buf[len] = '\0'; |
...
This compliant solution ensures there is no overflow by reading in only sizeof(buf)-1
characters. It also properly checks to see if an error has occurred.:
Code Block | ||||
---|---|---|---|---|
| ||||
enum { BUFFERSIZE = 1024 }; char buf[BUFFERSIZE]; ssize_t len = readlink("/usr/bin/perl", buf, sizeof(buf)-1); if (len != -1) { buf[len] = '\0'; } else { /* handle error condition */ } |
...
Failing to properly null-terminate the result of readlink()
can result in abnormal program termination and buffer-overflow vulnerabilities.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
POS30-C | high | probable | medium | P12 | L1 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Astrée |
| Supported: Can be checked with appropriate analysis stubs. | |||||||
Axivion Bauhaus Suite |
| CertC-POS30 | |||||||
CodeSonar |
| LANG.MEM.BO | Buffer Overrun | ||||||
Compass/ROSE |
Coverity |
| READLINK | Implemented | ||||||
Helix QAC |
| C5033 | |||||||
Klocwork |
| ABV.GENERAL | |||||||
Parasoft C/C++test |
| CERT_C-POS30-a | Avoid overflow due to reading a not zero terminated string | ||||||
| CERT C: Rule POS30-C | Checks for misuse of readlink() (rule partially covered) |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
Key here (explains table format and definitions)
...
Improper null termination |
...
2017-06-13: CERT: Rule subset of CWE |
CERT-CWE Mapping Notes
Key here for mapping notes
CWE-170 and POS30-C
CWE-170 = Union( POS30-C, list) where list =
- Non-null terminated strings fed to functions other than POSIX readlink()
Bibliography
...