Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of sprintf/snprintf is more secure?

I wish to know which of these two options is the more secure one to use:

#define MAXLEN 255 char buff[MAXLEN + 1] 
  1. sprintf(buff, "%.*s", MAXLEN, name)

  2. snprintf(buff, MAXLEN, "%s", name)

My understanding is that both are same. Please suggest.

like image 564
Arpit Avatar asked Sep 06 '11 06:09

Arpit


People also ask

Is Snprintf safer than sprintf?

Snprintf is more secure and if the string number overruns the characters, the string is protected in the buffer even if the format is different. It works with n characters and nth location and hence the location of null character is not considered at all. Allocation of null character memory is preserved in sprintf.

Is sprintf secure?

Warning: The sprintf function can be dangerous because it can potentially output more characters than can fit in the allocation size of the string s . Remember that the field width given in a conversion specification is only a minimum value.

Is sprintf vulnerable to buffer overflow?

The sprintf() function facilitates unbounded copying of text, in turn leaving the buffer susceptible to overflow attack.

What is the difference between sprintf and Sprintf_s?

One main difference between sprintf_s and sprintf is that sprintf_s checks the format string for valid formatting characters, whereas sprintf only checks if the format string or buffer are NULL pointers.


1 Answers

The two expressions you gave are not equivalent: sprintf takes no argument specifying the maximum number of bytes to write; it simply takes a destination buffer, a format string, and a bunch of arguments. Therefore, it may write more bytes than your buffer has space for, and in so doing write arbitrary code. The %.*s is not a satisfactory solution because:

  1. When the format specifier refers to length, it's referring to the equivalent of strlen; this is a measure of the number of characters in the string, not its length in memory (i.e. it doesn't count the null terminator).
  2. Any change in the format string (adding a newline, for example) will change the behavior of the sprintf version with respect to buffer overflows. With snprintf, a fixed, clear maximum is set regardless of changes in the format string or input types.
like image 138
azernik Avatar answered Oct 03 '22 00:10

azernik