作者:M0rk
作者博客:https://kevien.github.io/
TL;DR
緩衝區溢出除了典型的棧溢出和堆溢出外,還有一種發生在bss段上的,bss屬於數據段的一種,通常用來保存未初始化的全局靜態變量。wiki
測試環境ubuntu14.04X86.
vul code snippet
from game_of_chance.c
// Custom user struct to store information about users
struct user {
int uid;
int credits;
int highscore;
char name[100];
int (*current_game) ();
};
...
struct user player; // Player struct
其中game_of_chance 是如下圖的一個小遊戲
如上的代碼片段中用一個函數指針保存了上次玩了哪個遊戲,這個指針保存在user的結構體中,且被聲明為全局變量,這意味着user這個結構體變量保存在bss數據段。其中結構體中固定為100字節的name變量保存了用戶的姓名,且這個name是可以被input_name()這個函數所控制的,如下:
void input_name() {
char *name_ptr, input_char='/n';
while(input_char == '/n') // Flush any leftover
scanf("%c", &input_char); // newline chars.
name_ptr = (char *) &(player.name); // name_ptr = player name's address
while(input_char != '/n') { // Loop until newline.
*name_ptr = input_char; // Put the input char into name field.
scanf("%c", &input_char); // Get the next char.
name_ptr++; // Increment the name pointer.
}
*name_ptr = 0; // Terminate the string.
}
這個函數會接收用戶輸入的名字直到用戶輸入換行符,所以這裡並沒有有效的限制用戶輸入,就意味着可以被利用,此外我們覆蓋之後還需要程序去調用這個函數指針,這個功能可以發生在下面代碼的6、8或者10行以及play_the_game()函數中,代碼片段如下:
if((choice < 1) || (choice > 7))
printf("/n[!!] The number %d is an invalid selection./n/n", choice);
else if (choice < 4) { // Othewise, choice was a game of some sort.
if(choice != last_game) { // If the function ptr isn't set
if(choice == 1) // then point it at the selected game
player.current_game = pick_a_number;
else if(choice == 2)
player.current_game = dealer_no_match;
else
player.current_game = find_the_ace;
last_game = choice; // and set last_game.
}
play_the_game(); // Play the game.
}
漏洞利用
如果last_game 未設置,函數指針current_game 會被指向成0或者-1,這時不會觸發漏洞,後面last_game被設置成1,當修改完名字完成對current_game覆蓋再玩遊戲1的時候,進入play_the_game()函數,play_the_game()會有current_game指針變量的調用,此時漏洞即觸發!!!
reference
《Hacking the art of exploitation》0x342