什么是格式化字符串攻擊?
format string attack
https://www.owasp.org/index.php/Format_string_attack
首先攻擊發生在 格式化字符串所涉及的函數(例如 printf), 其次用戶輸入字符串提交后作為格式化字符串參數執行。
攻擊者可以執行代碼, 讀取棧空間、 寫棧空間、 導致進行段錯誤(segment fault),或者導致其他的威脅到計算機安全和穩定性的新的行為。
舉例子
正確例子,其中 "Bob %%x %%x" 是合法的輸入。
#include <stdio.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define snprintf _snprintf int main (int argc, char **argv) { char buf [100]; int x = 1; //snprintf ( buf, sizeof buf, "Bob %x %x" ) ; //bad snprintf ( buf, sizeof buf, "Bob %%x %%x" ) ; //good buf [ sizeof buf -1 ] = 0; printf ( "buf = %s\n", buf ); printf ( "Buffer size is: (%d) \nData input: %s \n" , strlen (buf) , buf ) ; printf ( "X equals: %d/ in hex: %#x\nMemory address for x: (%p) \n" , x, x, &x) ; return 0 ; }
輸出
------ 分割線 ------
邪惡的例子, 輸入 "Bob %x %x" 是非法的, 會導致snprintf函數繼續讀取棧數據
#include <stdio.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define snprintf _snprintf int main (int argc, char **argv) { char buf [100]; int x = 1; snprintf ( buf, sizeof buf, "Bob %x %x" ) ; //bad //snprintf ( buf, sizeof buf, "Bob %%x %%x" ) ; //good buf [ sizeof buf -1 ] = 0; printf ( "buf = %s\n", buf ); printf ( "Buffer size is: (%d) \nData input: %s \n" , strlen (buf) , buf ) ; printf ( "X equals: %d/ in hex: %#x\nMemory address for x: (%p) \n" , x, x, &x) ; return 0 ; }
輸出:
防格式化字符串攻擊
1、 對於客戶端提交過來的, 格式化字符串進行過濾, 將%刪除, 破壞掉格式化字符串的形式。 缺點是改變客戶端的提交數據完整性。但是可以保證此數據, 不管輸出在格式化函數 或者 非格式化函數中, 都沒有問題。
2、 對於客戶端提交過來的, 格式化字符串進行轉義, 對所有的%字符,前面都添加一個%, 可以保持客戶端提交的數據完整性。 但是對於這種輸入, 放在非格式化函數中, 會多出%。
Parameters | Output | Passed as |
---|---|---|
%% | % character (literal) | Reference |
%p | External representation of a pointer to void | Reference |
%d | Decimal | Value |
%c | Character | |
%u | Unsigned decimal | Value |
%x | Hexadecimal | Value |
%s | String | Reference |
%n | Writes the number of characters into a pointer | Reference |
3、 預防手段, 對於格式化字符串的函數, 在編碼時候,需要100%注意不要將 客戶端輸入的 字符串作為格式化字符串, 更加嚴格寫法, 只將常量字符串作為 格式化字符串, 即將需要的格式寫死在程序中!!
附錄格式化字符串涉及的函數
fprint | Writes the printf to a file |
printf | Output a formatted string |
sprintf | Prints into a string |
snprintf | Prints into a string checking the length |
vfprintf | Prints the a va_arg structure to a file |
vprintf | Prints the va_arg structure to stdout |
vsprintf | Prints the va_arg to a string |
vsnprintf | Prints the va_arg to a string checking the length |