security - gcc -D_FORTIFY_SOURCE=1 和 -D_FORTIFY_SOURCE=2 之间的区别

标签 security gcc glibc fortify-source

有人能指出 gcc -D_FORTIFY_SOURCE=1 和 -D_FORTIFY_SOURCE=2 之间的区别吗?我想 =2 更安全?我无法找到逐点列出差异的列表。

我还了解到,-D_FORTIFY_SOURCE=2 应与-O2 一起使用,否则并非所有功能都可用。另外,在这里我还没有找到详细指定回归的列表。我特别有兴趣使用 -Os 进行编译,因为目标是没有那么多闪存的设备。

欢迎提供有关记录位置的任何提示!

最佳答案

来自功能测试宏的手册页 ( man 7 feature_test_macros )

_FORTIFY_SOURCE (since glibc 2.3.4)

Defining this macro causes some lightweight checks to be performed to detect some buffer overflow errors when employing various string and memory manipulation functions (for example, memcpy, memset, stpcpy, strcpy, strncpy, strcat, strncat, sprintf, snprintf, vsprintf, vsnprintf, gets, and wide character variants thereof). For some functions, argument consistency is checked; for example, a check is made that open has been supplied with a mode argument when the specified flags include O_CREAT. Not all problems are detected, just some common cases.

If _FORTIFY_SOURCE is set to 1, with compiler optimization level 1 (gcc -O1) and above, checks that shouldn't change the behavior of conforming programs are performed.

With _FORTIFY_SOURCE set to 2, some more checking is added, but some conforming programs might fail.

Some of the checks can be performed at compile time (via macros logic implemented in header files), and result in compiler warnings; other checks take place at run time, and result in a run-time error if the check fails.

Use of this macro requires compiler support, available with gcc since version 4.0.

此外,文章Enhance application security with FORTIFY_SOURCE (2014 年 3 月)说:

  • gcc -D_FORTIFY_SOURCE=1仅在编译时添加检查(某些 header 是必需的,如 #include <string.h> )
  • gcc -D_FORTIFY_SOURCE=2还添加了运行时检查(检测到缓冲区溢出会终止程序)

本质上,_FORTIFY_SOURCE level 2 更安全,但是风险稍高的编译策略;如果您使用它,请确保对编译的代码进行非常强大的回归测试,以证明编译器没有引入任何意外行为。

关于security - gcc -D_FORTIFY_SOURCE=1 和 -D_FORTIFY_SOURCE=2 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13517526/

相关文章:

c - 用宏初始化结构

c - libc.so.6 在 Linux 内核中的相关性

java - 为什么两个相同的文本生成不同的密文

java - 使用 Java 存储 SHA2 密码

php - 服务器端执行用户提交的代码

c - Berkeley Sockets,打破别名规则?

C++: "illogical"析构函数行为

qt - qt 4.6 应用程序可以运行的最旧的 glib 版本是什么

c - 在汇编中使用 fgets 时出现段错误错误?

mysql - 设计困境 : If e-mail address already used, 发送电子邮件 "e-mail address already registered",但无法发送,因为无法将重复项添加到表中