lib/vsprintf.c: eliminate potential race in string()
authorRasmus Villemoes <[email protected]>
Sat, 16 Jan 2016 00:58:34 +0000 (16:58 -0800)
committerLinus Torvalds <[email protected]>
Sat, 16 Jan 2016 19:17:26 +0000 (11:17 -0800)
If the string corresponding to a %s specifier can change under us, we
might end up copying a \0 byte to the output buffer.  There might be
callers who expect the output buffer to contain a genuine C string whose
length is exactly the snprintf return value (assuming truncation hasn't
happened or has been checked for).

We can avoid this by only passing over the source string once, stopping
the first time we meet a nul byte (or when we reach the given
precision), and then letting widen_string() handle left/right space
padding.  As a small bonus, this code reuse also makes the generated
code slightly smaller.

Signed-off-by: Rasmus Villemoes <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Andy Shevchenko <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Joe Perches <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Maurizio Lombardi <[email protected]>
Cc: Tejun Heo <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
lib/vsprintf.c

index 854d597ba23ca61f494c2a5103e2f6aa23b640cd..c537a73a62e858ec1fe695a34ae4a33bdbf4a3f4 100644 (file)
@@ -560,32 +560,22 @@ char *widen_string(char *buf, int n, char *end, struct printf_spec spec)
 static noinline_for_stack
 char *string(char *buf, char *end, const char *s, struct printf_spec spec)
 {
-       int len, i;
+       int len = 0;
+       size_t lim = spec.precision;
 
        if ((unsigned long)s < PAGE_SIZE)
                s = "(null)";
 
-       len = strnlen(s, spec.precision);
-
-       if (!(spec.flags & LEFT)) {
-               while (len < spec.field_width--) {
-                       if (buf < end)
-                               *buf = ' ';
-                       ++buf;
-               }
-       }
-       for (i = 0; i < len; ++i) {
-               if (buf < end)
-                       *buf = *s;
-               ++buf; ++s;
-       }
-       while (len < spec.field_width--) {
+       while (lim--) {
+               char c = *s++;
+               if (!c)
+                       break;
                if (buf < end)
-                       *buf = ' ';
+                       *buf = c;
                ++buf;
+               ++len;
        }
-
-       return buf;
+       return widen_string(buf, len, end, spec);
 }
 
 static noinline_for_stack