为什么我使用fprintf在这个C代码中收到警告?

时间:2021-09-01 22:57:38
fprintf(pFile,msg.c_str());

why do I get a warning in Xcode :

为什么我在Xcode中收到警告:

Format string is not a string literal (potentially insecure)

I assume I get this warning to prevent attacks were msg contains some thing like %s which stream the stack to the screen until it gets to null termination. Is there any safe way to use fprintf in this case?

我假设我得到这个警告,以防止攻击是msg包含一些像%s的东西,它将堆栈流到屏幕,直到它终止为空。在这种情况下有没有安全的方法来使用fprintf?

2 个解决方案

#1


13  

You can either give a format string,

你可以给一个格式字符串,

fprintf(pFile, "%s", msg.c_str());

or use fputs,

或使用fputs,

fputs(msg.c_str(), pFile);

#2


10  

The reason why your compiler warned you is that your way of printing a string could lead to a vulnerability called "format string exploit" if the user is able to somehow influence the contents of msg to an extend where he could put in his own format specifiers ("%n", etc). The suggested answer (fprintf(pFile, "%s", msg.c_str());) fixes this, as the format string is now constant.

您的编译器警告您的原因是您打印字符串的方式可能导致称为“格式字符串漏洞利用”的漏洞,如果用户能够以某种方式影响msg的内容到他可以放入他自己的格式说明符的范围内(“%n”等)。建议的答案(fprintf(pFile,“%s”,msg.c_str());)解决了这个问题,因为格式字符串现在是常量。

You can read more about format string exploits on here: http://julianor.tripod.com/bc/formatstring-1.2.pdf

您可以在此处阅读有关格式字符串漏洞的更多信息:http://julianor.tripod.com/bc/formatstring-1.2.pdf

#1


13  

You can either give a format string,

你可以给一个格式字符串,

fprintf(pFile, "%s", msg.c_str());

or use fputs,

或使用fputs,

fputs(msg.c_str(), pFile);

#2


10  

The reason why your compiler warned you is that your way of printing a string could lead to a vulnerability called "format string exploit" if the user is able to somehow influence the contents of msg to an extend where he could put in his own format specifiers ("%n", etc). The suggested answer (fprintf(pFile, "%s", msg.c_str());) fixes this, as the format string is now constant.

您的编译器警告您的原因是您打印字符串的方式可能导致称为“格式字符串漏洞利用”的漏洞,如果用户能够以某种方式影响msg的内容到他可以放入他自己的格式说明符的范围内(“%n”等)。建议的答案(fprintf(pFile,“%s”,msg.c_str());)解决了这个问题,因为格式字符串现在是常量。

You can read more about format string exploits on here: http://julianor.tripod.com/bc/formatstring-1.2.pdf

您可以在此处阅读有关格式字符串漏洞的更多信息:http://julianor.tripod.com/bc/formatstring-1.2.pdf