Why is printf with a single argument (without conversion specifiers) deprecated?

主宰稳场 提交于 2019-11-27 17:39:13
Jabberwocky

printf("Hello World!"); is IMHO not vulnerable but consider this:

const char *str;
...
printf(str);

If str happens to point to a string containing %s format specifiers, your program will exhibit undefined behaviour (mostly a crash), whereas puts(str) will just display the string as is.

Example:

printf("%s");   //undefined behaviour (mostly crash)
puts("%s");     // displays "%s"

printf("Hello world");

is fine and has no security vulnerability.

The problem lies with:

printf(p);

where p is a pointer to an input that is controlled by the user. It is prone to format strings attacks: user can insert conversion specifications to take control of the program, e.g., %x to dump memory or %n to overwrite memory.

Note that puts("Hello world") is not equivalent in behavior to printf("Hello world") but to printf("Hello world\n"). Compilers usually are smart enough to optimize the latter call to replace it with puts.

Further to the other answers, printf("Hello world! I am 50% happy today") is an easy bug to make, potentially causing all manner of nasty memory problems (it's UB!).

It's just simpler, easier and more robust to "require" programmers to be absolutely clear when they want a verbatim string and nothing else.

And that's what printf("%s", "Hello world! I am 50% happy today") gets you. It's entirely foolproof.

(Steve, of course printf("He has %d cherries\n", ncherries) is absolutely not the same thing; in this case, the programmer is not in "verbatim string" mindset; she is in "format string" mindset.)

I'll just add a bit of information regarding the vulnerability part here.

It's said to be vulnerable because of printf string format vulnerability. In your example, where the string is hardcoded, it's harmless (even if hardcoding strings like this is never fully recommended). But specifying the parameter's types is a good habit to take. Take this example:

If someone puts format string character in your printf instead of a regular string (say, if you want to print the program stdin), printf will take whatever he can on the stack.

It was (and still is) very used to exploit programs into exploring stacks to access hidden information or bypass authentication for example.

Example (C):

int main(int argc, char *argv[])
{
    printf(argv[argc - 1]); // takes the first argument if it exists
}

if I put as input of this program "%08x %08x %08x %08x %08x\n"

printf ("%08x %08x %08x %08x %08x\n"); 

This instructs the printf-function to retrieve five parameters from the stack and display them as 8-digit padded hexadecimal numbers. So a possible output may look like:

40012980 080628c4 bffff7a4 00000005 08059c04

See this for a more complete explanation and other examples.

Konstantin Weitz

Calling printf with literal format strings is safe and efficient, and there exist tools to automatically warn you if your invocation of printf with user provided format strings is unsafe.

The most severe attacks on printf take advantage of the %n format specifier. In contrast to all other format specifiers, e.g. %d, %n actually writes a value to a memory address provided in one of the format arguments. This means that an attacker can overwrite memory and thus potentially take control of your program. Wikipedia provides more detail.

If you call printf with a literal format string, an attacker cannot sneak a %n into your format string, and you are thus safe. In fact, gcc will change your call to printf into a call to puts, so there litteraly isn't any difference (test this by running gcc -O3 -S).

If you call printf with a user provided format string, an attacker can potentially sneak a %n into your format string, and take control of your program. Your compiler will usually warn you that his is unsafe, see -Wformat-security. There are also more advanced tools that ensure that an invocation of printf is safe even with user provided format strings, and they might even check that you pass the right number and type of arguments to printf. For example, for Java there is Google's Error Prone and the Checker Framework.

This is misguided advice. Yes, if you have a run-time string to print,

printf(str);

is quite dangerous, and you should always use

printf("%s", str);

instead, because in general you can never know whether str might contain a % sign. However, if you have a compile-time constant string, there's nothing whatsoever wrong with

printf("Hello, world!\n");

(Among other things, that is the most classic C program ever, literally from the C programming book of Genesis. So anyone deprecating that usage is being rather heretical, and I for one would be somewhat offended!)

A rather nasty aspect of printf is that even on platforms where the stray memory reads could only cause limited (and acceptable) harm, one of the formatting characters, %n, causes the next argument to be interpreted as a pointer to a writable integer, and causes the number of characters output thus far to be stored to the variable identified thereby. I've never used that feature myself, and sometimes I use lightweight printf-style methods which I've written to include only the features I actually use (and don't include that one or anything similar) but feeding standard printf functions strings received from untrustworthy sources may expose security vulnerabilities beyond the ability to read arbitrary storage.

Since no one has mentioned, I'd add a note regarding their performance.

Under normal circumstances, assuming no compiler optimisations are used (i.e. printf() actually calls printf() and not fputs()), I would expect printf() to perform less efficiently, especially for long strings. This is because printf() has to parse the string to check if there are any conversion specifiers.

To confirm this, I have run some tests. The testing is performed on Ubuntu 14.04, with gcc 4.8.4. My machine uses an Intel i5 cpu. The program being tested is as follows:

#include <stdio.h>
int main() {
    int count = 10000000;
    while(count--) {
        // either
        printf("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM");
        // or
        fputs("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM", stdout);
    }
    fflush(stdout);
    return 0;
}

Both are compiled with gcc -Wall -O0. Time is measured using time ./a.out > /dev/null. The following is the result of a typical run (I've run them five times, all results are within 0.002 seconds).

For the printf() variant:

real    0m0.416s
user    0m0.384s
sys     0m0.033s

For the fputs() variant:

real    0m0.297s
user    0m0.265s
sys     0m0.032s

This effect is amplified if you have a very long string.

#include <stdio.h>
#define STR "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
#define STR2 STR STR
#define STR4 STR2 STR2
#define STR8 STR4 STR4
#define STR16 STR8 STR8
#define STR32 STR16 STR16
#define STR64 STR32 STR32
#define STR128 STR64 STR64
#define STR256 STR128 STR128
#define STR512 STR256 STR256
#define STR1024 STR512 STR512
int main() {
    int count = 10000000;
    while(count--) {
        // either
        printf(STR1024);
        // or
        fputs(STR1024, stdout);
    }
    fflush(stdout);
    return 0;
}

For the printf() variant (ran three times, real plus/minus 1.5s):

real    0m39.259s
user    0m34.445s
sys     0m4.839s

For the fputs() variant (ran three times, real plus/minus 0.2s):

real    0m12.726s
user    0m8.152s
sys     0m4.581s

Note: After inspecting the assembly generated by gcc, I realised that gcc optimises the fputs() call to an fwrite() call, even with -O0. (The printf() call remains unchanged.) I am not sure whether this will invalidate my test, as the compiler calculates the string length for fwrite() at compile-time.

Ábrahám Endre
printf("Hello World\n")

automatically compiles to the equivalent

puts("Hello World")

you can check it with diassembling your executable:

push rbp
mov rbp,rsp
mov edi,str.Helloworld!
call dword imp.puts
mov eax,0x0
pop rbp
ret

using

char *variable;
... 
printf(variable)

will lead to security issues, don't ever use printf that way!

so your book is actually correct, using printf with one variable is deprecated but you can still use printf("my string\n") because it will automatically become puts

Patrick Schlüter

For gcc it is possible to enable specific warnings for checking printf() and scanf().

The gcc documentation states:

-Wformat is included in -Wall. For more control over some aspects of format checking, the options -Wformat-y2k, -Wno-format-extra-args, -Wno-format-zero-length, -Wformat-nonliteral, -Wformat-security, and -Wformat=2 are available, but are not included in -Wall.

The -Wformat which is enabled within the -Wall option does not enable several special warnings that help to find these cases:

  • -Wformat-nonliteral will warn if you do not pass a string litteral as format specifier.
  • -Wformat-security will warn if you pass a string that might contain a dangerous construct. It's a subset of -Wformat-nonliteral.

I have to admit that enabling -Wformat-security revealed several bugs we had in our codebase (logging module, error handling module, xml output module, all had some functions that could do undefined things if they had been called with % characters in their parameter. For info, our codebase is now around 20 years old and even if we were aware of these kind of problems, we were extremely surprised when we enabled these warnings how many of these bugs were still in the codebase).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!