[英]C buffer overflow getting Segmentation Fault
我正在嘗試為我的安全 class 做一個緩沖區溢出,我們不允許調用任何 function,我們需要在沒有分段錯誤的情況下跳轉到秘密 function 並返回。 我編寫了下面的代碼並成功跳轉到秘密,但我遇到了分段錯誤。 如何成功終止程序? 或者是否可以只寫入單個地址而不是 for 循環,當我嘗試時它沒有改變任何東西。
#include <stdio.h>
void secret()
{
printf("now inside secret()!\n");
}
void entrance()
{
int doNotTouch[10];
// can only modify this section BEGIN
// cant call secret(), maybe use secret (pointer to function)
for (int i = 0; i < 14; i++) {
*(doNotTouch + i) = (int) &secret;
}
// can only modify this section END
printf("now inside entrance()!\n");
}
int main (int argc, char *argv[])
{
entrance();
return 0;
}
在一些半匯編程序中,假設某種 x86。 (BP 是 EBP 或 RBP 的偽代碼,假設您實際上並未針對 16 位模式進行編譯。32 位模式很可能因此int
與返回地址的寬度相同。)
; entrance:
; - stack has return address to main
push bp ; decrement SP by a pointer width
mov bp,sp
sub sp, 10*sizeof(int) ; reserve space for an array
;....
; doNotTouch[0] is probably at [bp - 10*sizeof(int)]
當您循環到 14 時,您首先在 i==10 處覆蓋保存的 bp,然后將返回地址覆蓋到 main(這是正確的),然后再覆蓋一些最終導致 seg 錯誤的地址。 所以你只需要做*(doNotTouch + 11) = (int) &secret;
- 假設 int 是 function 指針的大小。 (或者如果編譯器為堆棧對齊或它自己的使用留下了間隙。在調試構建中,其他本地人將有堆棧插槽。覆蓋它們可能會導致無限循環超出范圍。)
然后跟隨您的 printf 然后 function 返回,但它不會返回 main 而是“跳轉”到secret
。
當secret
返回時,實際上是從main返回,但不能return 0;
所以秘密應該是:
int secret()
{
printf("now inside secret()!\n");
return 0;
}
免責聲明:“....我認為。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.