sprintf/snprintf 哪个更安全? [英] 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]
sprintf(buff, "%.*s", MAXLEN, name)
snprintf(buff, MAXLEN, "%s", name)
我的理解是两者是一样的.请提出建议.
My understanding is that both are same. Please suggest.
推荐答案
你给出的两个表达式不是等价的:sprintf
没有指定最大字节数的参数来写;它只需要一个目标缓冲区、一个格式字符串和一堆参数.因此,它可能会写入比缓冲区空间更多的字节,并在这样做时写入任意代码.%.*s
不是一个令人满意的解决方案,因为:
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:
- 当格式说明符指的是长度时,它指的是相当于
strlen
;这是字符串中字符数的度量,而不是它在内存中的长度(即它不计算空终止符). - 格式字符串的任何更改(例如,添加换行符)都将更改
sprintf
版本在缓冲区溢出方面的行为.使用snprintf
,无论格式字符串或输入类型如何变化,都会设置一个固定的、清晰的最大值.
- 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). - Any change in the format string (adding a newline, for example) will change the behavior of the
sprintf
version with respect to buffer overflows. Withsnprintf
, a fixed, clear maximum is set regardless of changes in the format string or input types.
这篇关于sprintf/snprintf 哪个更安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!