跳轉到內容

Linux 應用程式除錯技術/堆疊損壞

來自 Wikibooks,開放世界中的開放書籍

堆疊損壞很難診斷。幸運的是,gcc 4.x 可以檢測程式碼以檢查堆疊損壞

  • -fstack-protector 為包含“alloca”或具有 (signed 或 unsigned) char 陣列且大小 > 8 (SSP_BUFFER_SIZE) 的函式新增堆疊保護
  • -fstack-protector-strong 為更多函式新增堆疊保護,見下文
  • -fstack-protector-all 為所有函式新增堆疊保護

gcc 將新增保護變數和程式碼以檢查函式退出時的緩衝區溢位。一個簡單的例子

/* Compile with: gcc -ggdb -fstack-protector-all stacktest.c */

#include <stdio.h>
#include <string.h>
 
void bar(char* str) 
{
    char buf[4];
    strcpy(buf, str);
}
	 
void foo() 
{
    printf("It survived!");
}
	 
int main(void) 
{
    bar("Longer than 4.");
    foo();
    return 0;
}

執行時,程式將轉儲核心

$ ./a.out 
*** stack smashing detected ***: ./a.out terminated
Aborted (core dumped)
Core was generated by `./a.out'.
Program terminated with signal 6, Aborted.
#0  0x0000003684030265 in raise () from /lib64/libc.so.6
(gdb) bt full
#0  0x0000003684030265 in raise () from /lib64/libc.so.6
No symbol table info available.
#1  0x0000003684031d10 in abort () from /lib64/libc.so.6
No symbol table info available.
#2  0x000000368406a84b in __libc_message () from /lib64/libc.so.6
No symbol table info available.
#3  0x00000036840e8ebf in __stack_chk_fail () from /lib64/libc.so.6
No symbol table info available.
#4  0x0000000000400584 in bar (str=0x400715 "Longer than 4.") at stacktest.c:10
        buf =           "Long"
#5  0x00000000004005e3 in main () at stacktest.c:19
No locals.

-fstack-protector-strong

[編輯 | 編輯原始碼]

由谷歌新增到 gcc。

優勢 - 在犧牲少量安全性(對於使用 -fstack-protector-all 的場景)的同時獲得很大的效能提升

背景 - 有時堆疊保護過於簡單,而堆疊保護所有則過度殺傷,例如,為了構建我們的核心繫統之一,我們強制在所有編譯命令中新增“-fstack-protector-all”,這會導致原子和 arm 上的巨大效能損失(由於在函式序言和結語上的額外堆疊保護/檢查指令)。系統安全團隊認為使用“-fstack-protector”不夠安全(僅“保護”<2% 的函式)。“-fstack-protector-strong”在“-fstack-protector”和“-fstack-protector-all”之間取得平衡。

為函式新增檢查

  • 如果任何區域性變數的地址作為賦值的 RHS(右值)的一部分被獲取
  • 或者如果任何區域性變數的地址作為函式引數的一部分被獲取。
  • 或者如果它包含一個數組,無論陣列型別或長度如何
  • 或者如果它包含一個結構體/聯合體,其中包含一個數組,無論陣列型別或長度如何。
  • 或者如果函式包含暫存器區域性變數

請參閱 http://gcc.gnu.org/ml/gcc-patches/2012-06/msg00974.html

進一步閱讀
[編輯 | 編輯原始碼]


從 gcc 4.9 及更高版本開始,您可以使用 ubsan 淨化器 進行邊界檢查。

華夏公益教科書