Split *s*printf(3) from printf(3), and document the snprintf(,-1,) is UB
Alejandro Colomar
maintainercover Split *s*printf(3) from printf(3), and document the snprintf(,-1,) is UB
Hi!
Serge and I were reviewing some code, and we realized that it seems quite easy to induce a buffer overflow using snprintf(3).
We solved our problems by checking that the size is non-negative in a wrapper inline function.
// vstprintf - va_list string truncate print formatted
inline int
vstprintf(char *restrict s, ssize_t size, const char *restrict fmt, va_list ap)
{
int len;
if (size <= 0 || size > INT_MAX) {
errno = EOVERFLOW;
return -1;
}
len = vsnprintf(s, size, fmt, ap);
if (len == -1) {
if (errno == EOVERFLOW)
errno = E2BIG;
return -1;
}
if (len >= size) {
errno = E2BIG;
return -1;
}
return len;
}[v]snprintf(3) seems to be even worse than I thought it was. Let's document this.
Alejandro Colomar (2):
man/man3/*printf.3: Split *s*printf(3) from printf(3) man/man3/snprintf.3: BUGS: snprintf(3) with a negative size is
essentially UB
man/man3/printf.3 | 223 +--------------------------- man/man3/snprintf.3 | 337 ++++++++++++++++++++++++++++++++++++++++++- man/man3/sprintf.3 | 2 +- man/man3/vsnprintf.3 | 2 +- man/man3/vsprintf.3 | 2 +- 5 files changed, 346 insertions(+), 220 deletions(-)
Range-diff:
-: --------- > 1: a654dcfc2 man/man3/*printf.3: Split *s*printf(3) from printf(3) -: --------- > 2: d00ed9434 man/man3/snprintf.3: BUGS: snprintf(3) with a negative size is essentially UB
base-commit: 2a5edb7e59ae024d1969e7379c078a58b5f50b80
Signature · 1 line
2.51.0
Alejandro Colomar
maintainerPATCH 1/2 man/man3/*printf.3: Split *s*printf(3) from printf(3)
--- man/man3/printf.3 | 223 +----------------------------- man/man3/snprintf.3 | 318 ++++++++++++++++++++++++++++++++++++++++++- man/man3/sprintf.3 | 2 +- man/man3/vsnprintf.3 | 2 +- man/man3/vsprintf.3 | 2 +- 5 files changed, 327 insertions(+), 220 deletions(-)
man/man3/printf.3 +7 -216
@@ -5,8 +5,9 @@ .\" .TH printf 3 (date) "Linux man-pages (unreleased)" .SH NAME -printf, fprintf, dprintf, sprintf, snprintf, vprintf, vfprintf, vdprintf, -vsprintf, vsnprintf \- formatted output conversion +printf, fprintf, dprintf, vprintf, vfprintf, vdprintf, +\- +formatted output conversion .SH LIBRARY Standard C library .RI ( libc ,\~ \-lc )
@@ -19,22 +20,12 @@ .SH SYNOPSIS .BI " const char *restrict " format ", ...);" .BI "int dprintf(int " fd , .BI " const char *restrict " format ", ...);" -.BI "int sprintf(char *restrict " str , -.BI " const char *restrict " format ", ...);" -.BR "int snprintf(" "size_t size;" -.BI " char " str "[restrict " size "], size_t " size , -.BI " const char *restrict " format ", ...);" .P .BI "int vprintf(const char *restrict " format ", va_list " ap ); .BI "int vfprintf(FILE *restrict " stream , .BI " const char *restrict " format ", va_list " ap ); .BI "int vdprintf(int " fd , .BI " const char *restrict " format ", va_list " ap ); -.BI "int vsprintf(char *restrict " str , -.BI " const char *restrict " format ", va_list " ap ); -.BR "int vsnprintf(" "size_t size;" -.BI " char " str "[restrict " size "], size_t " size , -.BI " const char *restrict " format ", va_list " ap ); .fi .P .RS -4
@@ -42,13 +33,6 @@ .SH SYNOPSIS .BR feature_test_macros (7)): .RE .P -.BR snprintf (), -.BR vsnprintf (): -.nf - _XOPEN_SOURCE >= 500 || _ISOC99_SOURCE - || /* glibc <= 2.19: */ _BSD_SOURCE -.fi -.P .BR dprintf (), .BR vdprintf (): .nf
@@ -74,14 +58,7 @@ .SH DESCRIPTION and .BR vfprintf () write output to the given output -.IR stream ; -.BR sprintf (), -.BR snprintf (), -.BR vsprintf (), -and -.BR vsnprintf () -write to the character string -.IR str . +.IR stream . .P The function .BR dprintf ()
@@ -94,26 +71,13 @@ .SH DESCRIPTION stream. .P The functions -.BR snprintf () -and -.BR vsnprintf () -write at most -.I size -bytes (including the terminating null byte (\[aq]\[rs]0\[aq])) to -.IR str . -.P -The functions .BR vprintf (), .BR vfprintf (), -.BR vdprintf (), -.BR vsprintf (), -.BR vsnprintf () +.BR vdprintf () are equivalent to the functions .BR printf (), .BR fprintf (), .BR dprintf (), -.BR sprintf (), -.BR snprintf (), respectively, except that they are called with a .I va_list instead of a variable number of arguments.
@@ -134,17 +98,6 @@ .SH DESCRIPTION the variable-length argument facilities of .BR stdarg (3)) are converted for output. -.P -C99 and POSIX.1-2001 specify that the results are undefined if a call to -.BR sprintf (), -.BR snprintf (), -.BR vsprintf (), -or -.BR vsnprintf () -would cause copying to take place between objects that overlap -(e.g., if the target string array and one of the supplied input arguments -refer to the same buffer). -See CAVEATS. .SS Format of the format string The format string is a character string, beginning and ending in its initial shift state, if any.
@@ -913,22 +866,6 @@ .SH RETURN VALUE Upon successful return, these functions return the number of bytes printed (excluding the null byte used to end output to strings). .P -The functions -.BR snprintf () -and -.BR vsnprintf () -do not write more than -.I size -bytes (including the terminating null byte (\[aq]\[rs]0\[aq])). -If the output was truncated due to this limit, then the return value -is the number of characters (excluding the terminating null byte) -which would have been written to the final string if enough space -had been available. -Thus, a return value of -.I size -or more means that the output was truncated. -(See also below under CAVEATS.) -.P On error, a negative value is returned, and
@@ -966,12 +903,8 @@ .SH ATTRIBUTES .nh .BR printf (), .BR fprintf (), -.BR sprintf (), -.BR snprintf (), .BR vprintf (), -.BR vfprintf (), -.BR vsprintf (), -.BR vsnprintf () +.BR vfprintf () T} Thread safety MT-Safe locale .TE .SH STANDARDS
@@ -980,17 +913,9 @@ .SH STANDARDS .TQ .BR printf () .TQ -.BR sprintf () -.TQ .BR vprintf () .TQ .BR vfprintf () -.TQ -.BR vsprintf () -.TQ -.BR snprintf () -.TQ -.BR vsnprintf () C11, POSIX.1-2008. .TP .BR dprintf ()
@@ -1003,36 +928,11 @@ .SH HISTORY .TQ .BR printf () .TQ -.BR sprintf () -.TQ .BR vprintf () .TQ .BR vfprintf () -.TQ -.BR vsprintf () C89, POSIX.1-2001. .TP -.BR snprintf () -.TQ -.BR vsnprintf () -SUSv2, C99, POSIX.1-2001. -.IP -Concerning the return value of -.BR snprintf (), -SUSv2 and C99 contradict each other: when -.BR snprintf () -is called with -.IR size =0 -then SUSv2 stipulates an unspecified return value less than 1, -while C99 allows -.I str -to be NULL in this case, and gives the return value (as always) -as the number of characters that would have been written in case -the output string has been large enough. -POSIX.1-2001 and later align their specification of -.BR snprintf () -with C99. -.TP .BR dprintf () .TQ .BR vdprintf ()
@@ -1091,39 +991,6 @@ .SH HISTORY .B m conversion specifier, that is .IR %#m . -.SH CAVEATS -Some programs imprudently rely on code such as the following -.P -.in +4n -.EX -sprintf(buf, "%s some further text", buf); -.EE -.in -.P -to append text to -.IR buf . -However, the standards explicitly note that the results are undefined -if source and destination buffers overlap when calling -.BR sprintf (), -.BR snprintf (), -.BR vsprintf (), -and -.BR vsnprintf (). -.\" http://sourceware.org/bugzilla/show_bug.cgi?id=7075 -Depending on the version of -.BR gcc (1) -used, and the compiler options employed, calls such as the above will -.B not -produce the expected results. -.P -The glibc implementation of the functions -.BR snprintf () -and -.BR vsnprintf () -conforms to the C99 standard, that is, behaves as described above, -since glibc 2.1. -Until glibc 2.0.6, they would return \-1 -when the output was truncated. .\" .SH HISTORY .\" UNIX V7 defines the three routines .\" .BR printf (),
@@ -1158,37 +1025,6 @@ .SH CAVEATS .\" .BR vdprintf () .\" that print to a file descriptor instead of a stream. .SH BUGS -Because -.BR sprintf () -and -.BR vsprintf () -assume an arbitrarily long string, -callers must be careful not to overflow the actual space; -this is often impossible to assure. -Note that the length of the strings produced is locale-dependent -and difficult to predict. -Use -.BR snprintf () -and -.BR vsnprintf () -instead (or -.BR asprintf (3) -and -.BR vasprintf (3)). -.\" .P -.\" Linux libc4.[45] does not have a -.\" .BR snprintf (), -.\" but provides a libbsd that contains an -.\" .BR snprintf () -.\" equivalent to -.\" .BR sprintf (), -.\" that is, one that ignores the -.\" .I size -.\" argument. -.\" Thus, the use of -.\" .BR snprintf () -.\" with early libc4 leads to serious security problems. -.P Code such as .BI printf( foo ); often indicates a bug, since
@@ -1256,58 +1092,13 @@ .SH EXAMPLES .in .P one might obtain "Sonntag, 3.\& Juli, 10:02". -.P -To allocate a sufficiently large string and print into it -(code correct for both glibc 2.0 and glibc 2.1): -.P -.EX -#include <stdio.h> -#include <stdlib.h> -#include <stdarg.h> -\& -char * -make_message(const char *fmt, ...) -{ - int n = 0; - size_t size = 0; - char *p = NULL; - va_list ap; -\& - /* Determine required size. */ -\& - va_start(ap, fmt); - n = vsnprintf(p, size, fmt, ap); - va_end(ap); -\& - if (n < 0) - return NULL; -\& - size = (size_t) n + 1; /* One extra byte for \[aq]\[rs]0\[aq] */ - p = malloc(size); - if (p == NULL) - return NULL; -\& - va_start(ap, fmt); - n = vsnprintf(p, size, fmt, ap); - va_end(ap); -\& - if (n < 0) { - free(p); - return NULL; - } -\& - return p; -} -.EE -.P -If truncation occurs in glibc versions prior to glibc 2.0.6, -this is treated as an error instead of being handled gracefully. .SH SEE ALSO .BR printf (1), .BR asprintf (3), .BR puts (3), .BR scanf (3), .BR setlocale (3), +.BR snprintf (3), .BR strfromd (3), .BR wcrtomb (3), .BR wprintf (3),
man/man3/snprintf.3 +317 -1
318 lines not on this page · raw message
man/man3/sprintf.3 +1 -1
@@ -1 +1 @@ -.so man3/printf.3 +.so man3/snprintf.3
man/man3/vsnprintf.3 +1 -1
@@ -1 +1 @@ -.so man3/printf.3 +.so man3/snprintf.3
man/man3/vsprintf.3 +1 -1
@@ -1 +1 @@ -.so man3/printf.3 +.so man3/snprintf.3
Signature · 1 line
2.51.0
Alejandro Colomar
maintainerPATCH 2/2 man/man3/snprintf.3: BUGS: snprintf(3) with a negative size is essentially UB
In reply to Alejandro Colomar--- man/man3/snprintf.3 | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-)
man/man3/snprintf.3 +20 -1
@@ -54,7 +54,8 @@ .SH DESCRIPTION write at most .I size bytes (including the terminating null byte (\[aq]\[rs]0\[aq])) to -.IR str . +.I str +(but see BUGS). .P The functions .BR vsprintf ()
@@ -242,6 +243,24 @@ .SS sprintf(), vsprintf() .BR asprintf (3) and .BR vasprintf (3)). +.SS snprintf(), vsnprintf() +If +.I size +is negative, +these functions will behave +as if the size was some unreasonably high value. +This turns these functions essentially equivalent to +.RB [ v ] sprintf (), +and thus likely to overflow the buffer. +It is the programmer's responsibility to pass a non-negative +.IR size . +.P +For historic reasons, +the +.I size +parameter is of type +.IR int , +which makes it relatively easy to pass a negative value. .\" .P .\" Linux libc4.[45] does not have a .\" .BR snprintf (),
Signature · 1 line
2.51.0
Alejandro Colomar
maintainerRe: [PATCH 2/2] man/man3/snprintf.3: BUGS: snprintf(3) with a negative size is essentially UB
Hi,
Here's how this patch changes the formatted page:
$ MANWIDTH=72 diffman-git HEAD
--- HEAD^:man/man3/snprintf.3
+++ HEAD:man/man3/snprintf.3
@@ -33,7 +33,8 @@ DESCRIPTION
to the character string str instead of a stream. The functions snprintf() and vsnprintf() write at most size bytes
- (including the terminating null byte ('\0')) to str.
+ (including the terminating null byte ('\0')) to str (but see
+ BUGS). The functions vsprintf() and vsnprintf() are equivalent to the functions sprintf() and snprintf(), respectively, except that they
@@ -132,6 +133,16 @@ BUGS
Use snprintf() and vsnprintf() instead (or asprintf(3) and vasprintf(3)).
+ snprintf(), vsnprintf()
+ If size is negative, these functions will behave as if the size + was some unreasonably high value. This turns these functions es‐ + sentially equivalent to [v]sprintf(), and thus likely to overflow + the buffer. It is the programmer’s responsibility to pass a non‐ + negative size.
+
+ For historic reasons, the size parameter is of type int, which
+ makes it relatively easy to pass a negative value.
+
EXAMPLES
To allocate a sufficiently large string and print into it (code correct for both glibc 2.0 and glibc 2.1):
Cheers,
Alex
Quoted 48 lines · Alejandro Colomar
Reported-by Serge Hallyn <[email protected]>Signed-off-by Alejandro Colomar <[email protected]>--- man/man3/snprintf.3 | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-)man/man3/snprintf.3 +20
-1@@ -54,7 +54,8 @@ .SH DESCRIPTION write at most .I size bytes (including the terminating null byte (\[aq]\[rs]0\[aq])) to -.IR str . +.I str +(but see BUGS). .P The functions .BR vsprintf ()@@ -242,6 +243,24 @@ .SS sprintf(), vsprintf() .BR asprintf (3) and .BR vasprintf (3)). +.SS snprintf(), vsnprintf() +If +.I size +is negative, +these functions will behave +as if the size was some unreasonably high value. +This turns these functions essentially equivalent to +.RB [ v ] sprintf (), +and thus likely to overflow the buffer. +It is the programmer's responsibility to pass a non-negative +.IR size . +.P +For historic reasons, +the +.I size +parameter is of type +.IR int , +which makes it relatively easy to pass a negative value. .\" .P .\" Linux libc4.[45] does not have a .\" .BR snprintf (),Signature · 1 line
2.51.0
Signature · 1 line
<https://www.alejandro-colomar.es>
Alejandro Colomar
maintainerRe: [PATCH 2/2] man/man3/snprintf.3: BUGS: snprintf(3) with a negative size is essentially UB
In reply to Alejandro ColomarHi,
Quoted 32 lines · Alejandro Colomar
Reported-by Serge Hallyn <[email protected]>Signed-off-by Alejandro Colomar <[email protected]>--- man/man3/snprintf.3 | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-)man/man3/snprintf.3 +10
-1@@ -54,7 +54,8 @@ .SH DESCRIPTION write at most .I size bytes (including the terminating null byte (\[aq]\[rs]0\[aq])) to -.IR str . +.I str +(but see BUGS). .P The functions .BR vsprintf ()@@ -242,6 +243,24 @@ .SS sprintf(), vsprintf() .BR asprintf (3) and .BR vasprintf (3)). +.SS snprintf(), vsnprintf() +If +.I size +is negative, +these functions will behave +as if the size was some unreasonably high value. +This turns these functions essentially equivalent to +.RB [ v ] sprintf (),
man/man3/snprintf.3 .SS sprintf(), vsprintf() · line 263
Quoted 10 lines
man/man3/snprintf.3 +10
-0+and thus likely to overflow the buffer. +It is the programmer's responsibility to pass a non-negative +.IR size . +.P +For historic reasons, +the +.I size +parameter is of type +.IR int , +which makes it relatively easy to pass a negative value.
Actually, I was completely wrong. The parameter is of type size_t. Only the return value is of type int.
Have a lovely day!
Alex
Quoted 6 lines
man/man3/snprintf.3 +0
-0.\" .P .\" Linux libc4.[45] does not have a .\" .BR snprintf (),Signature · 1 line
2.51.0
Signature · 1 line
<https://www.alejandro-colomar.es>
Re: [PATCH 2/2] man/man3/snprintf.3: BUGS: snprintf(3) with a negative size is essentially UB
Dec 6, 2025 07:32:46 Alejandro Colomar <[email protected]>:
Quoted 51 lines
Hi,
Quoted 32 lines · Alejandro Colomar
Reported-by Serge Hallyn <[email protected]>Signed-off-by Alejandro Colomar <[email protected]>---
man/man3/snprintf.3 | 21 ++++++++++++++++++++-1 file changed, 20 insertions(+), 1 deletion(-)man/man3/snprintf.3 +0
-0@@ -54,7 +54,8 @@ .SH DESCRIPTIONwrite at most
.I size
bytes (including the terminating null byte (\[aq]\[rs]0\[aq])) to -.IR str .
+.I str
+(but see BUGS).
.P
The functions
.BR vsprintf ()man/man3/snprintf.3 +0
-0@@ -242,6 +243,24 @@ .SS sprintf(), vsprintf() .BR asprintf (3)and
.BR vasprintf (3)).
+.SSsnprintf(),vsnprintf()man/man3/snprintf.3 +7
-0+If +.I size +is negative, +these functions will behave +as if the size was some unreasonably high value. +This turns these functions essentially equivalent to +.RB [ v ] sprintf (),man/man3/snprintf.3 .SS sprintf(), vsprintf() · line 263
Quoted 10 lines
man/man3/snprintf.3 +10
-0+and thus likely to overflow the buffer. +It is the programmer's responsibility to pass a non-negative +.IR size . +.P +For historic reasons, +the +.I size +parameter is of type +.IR int , +which makes it relatively easy to pass a negative value.Actually, I was completely wrong. The parameter is of type
size_t. Only the return value is of type int.
Quoted 3 lines
Have a lovely day!
Alex
Right, that's actually the danger. It's easy to pass in an int or ssize_t, and end up overflowing the buffer, even if you (the caller) check for > buflen in advance, by passing in a negative value. By the time you check the return value, it's too late.
"You just need to know (and not do that)", but if you are reviewing a patch and don't notice the extra s in ssize_t...
Alejandro Colomar
maintainerRe: [PATCH 2/2] man/man3/snprintf.3: BUGS: snprintf(3) with a negative size is essentially UB
Hi Serge,
Quoted 4 lines · Serge Hallyn
Quoted 4 lines
Actually, I was completely wrong. The parameter is of type
size_t. Only the return value is of type int.
Quoted 8 lines
Quoted 3 lines
Have a lovely day!
AlexRight, that's actually the danger. It's easy to pass in an int or
ssize_t, and end up overflowing the buffer, even if you (the caller) check for > buflen in advance, by passing in a negative value. By the time you check the return value, it's too late.
ssize_t should be safe, as it has the same width as size_t. It should be impossible to have a negative value in ssize_t, because objects can't grow past PTRDIFF_MAX, which is --at least in all platforms we care about-- exactly the same as SSIZE_MAX.
So, to pass a negative value, you would have to either write it literally, or do something really bad. malloc(3) can't possibly create an object that would result in a negative ssize_t.
The problem would only exist with int, because int is easy to overflow.
That is, the following code is fine:
ssize_t x = _Countof(buf); snprintf(buf, x, ...);
And it behaves exactly like this:
size_t x = _Countof(buf); snprintf(buf, x, ...);
However, the following is likely to result in a buffer overflow:
int x = _Countof(buf); snprintf(buf, x, ...);
Have a lovely day!
Alex
Quoted 1 line
"You just need to know (and not do that)", but if you are reviewing a patch and don't notice the extra s in
ssize_t...
Signature · 1 line
<https://www.alejandro-colomar.es>