简体   繁体   中英

Why is vsnprintf safe?

I have looked at this question as well as these PDFs' 1 and 2 , this page and pretty much understand what happens if I do this printf(SOME_TEST_STRING) . But what I do not understand is why exactly by ensuring the size of buffer vsnprintf becomes safe as compared to vsprintf ?

What happens in these 2 cases ?

Case 1

char buf[3];
vsprint(buf, "%s", args);

Case 2

char buf[3];
vsnprint(buf, sizeof buf, "%s", args);

In case 1, if the string you're formatting has a length of 3 or greater, you have a buffer overrun, vsprintf might write to memory past the storage of the buf array, which is undefined behavior, possibly causing havoc/security concerns/crashes/etc.

In case 2. vsnprintf knows how big the buffer that will contain the result is, and it will make sure not to go past that(instead truncating the result to fit within buf ).

It's because vsnprintf has an additional size_t count parameter that vsprintf (and other non-n *sprintf methods) does not have. The implementation uses this to ensure that the data it writes to your buffer will not run off the end.

Data that runs off the end of a buffer can result in data corruption, or when maliciously exploited can be used as a buffer overrun attack.

The "n" in vsnprintf() means it takes the max size of the output string to avoid a buffer overflow. This makes it safe from buffer overflow, but does not make it safe if the format string comes from unsanitized user input. If your user gives you a giant format string, you'll avoid overflowing the target string, but if the user gives you %s and you don't pass a C string in the argument list at compile time, you are still left with undefined behavior.

I'm not sure what the problem is, since your question basically contains the answer already.

By passing your buffer size to vsnprintf you provide that function with information about your buffer size. The function now knows where the buffer ends and can make sure that it does not write past the end of the buffer.

vsprintf does not have information about buffer size, which is why it does not know where the buffer ends and cannot prevent buffer overflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM