The function readlink()
does not null terminate its output.
The function readlink()
takes three arguments: linkname, buffer,
and buf_sz
. The function looks up the name of the file pointed to by the symbolic link linkname
and stores the resolved name to the second argument, buffer
. The function stores at most buf_sz
characters to buffer
. This function is unusual in the C library because it makes no effort to null terminate buffer
. Instead, it returns the number of characters it has written.
A typical misuse of readlink()
looks like this:
char buf[256];
len = readlink(lname, buf, sizeof(buf));
buf[len] = '\0';
len
is equal to sizeof(buf)
, the null terminator will be written one byte past the end of buf
.buf
large enough that it can always hold the result:
char buf[PATH_MAX+1];
len = readlink(lname, buf, sizeof(buf));
buf[len] = '\0';
PATH_MAX
represents the longest possible path for a file in the filesystem. (PATH_MAX
only bounds the longest possible relative path that can be passed to the kernel in a single call.) On most Unix and Linux systems, there is no easily-determined maximum length for a file path, and so the off-by-one buffer overflow risk is still present.readlink()
returns the same value that has been passed to its third argument, it is impossible to know whether the name is precisely that many bytes long, or whether readlink()
has truncated the name to avoid overrunning the buffer.[1] Standards Mapping - OWASP Top 10 2004 - (OWASP 2004) A5 Buffer Overflow
[2] Standards Mapping - Security Technical Implementation Guide Version 3 - (STIG 3) APP3590.1 CAT I
[3] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 249, CWE ID 560
[4] Standards Mapping - Payment Card Industry Data Security Standard Version 1.2 - (PCI 1.2) Requirement 6.3.1.1
[5] Standards Mapping - Payment Card Industry Data Security Standard Version 2.0 - (PCI 2.0) Requirement 6.5.2
[6] Standards Mapping - Payment Card Industry Data Security Standard Version 1.1 - (PCI 1.1) Requirement 6.5.5
[7] The GNU C Library Reference Manual The GNU Software Foundation