return to libc works in gdb but not when running alone

做~自己de王妃 提交于 2020-01-03 03:20:14

问题


I am trying return to libc trick with the following simple code:

#define SYSTEM_CALL_ADDR 0xb7ec5e50  /*my system call addr*/
#define EXIT_CALL_ADDR  0xb7ebbb80   /*my exit call addr*/
char shell[] = "/bin/sh";

int main(){
 int* p; 
 p = (int*)&p + 2;
 *p = SYSTEM_CALL_ADDR;

 p = (int*)&p + 3;
 *p = EXIT_CALL_ADDR;

 p = (int*)&p + 4;
 *p = shell;

 return 1;
}

Interestingly when I run this program, it ends with "Segmentation error", but if I debug it using gdb and run it step by step, it's totally fine, spawning a shell and then exiting program. Anybody meet this situation? or could somebody please guide me how to correct this? Thanks first. I am on ArchLinux kernel:2.6.33, gcc 4.5.0.


回答1:


gdb disables some of the buffer overflow exploit mitigation techniques such as ProPolice and address space layout randomization (ASLR).




回答2:


gdb sets the ADDR_NO_RANDOMIZE personality(2) to facilitate debugging.




回答3:


The crash occurs because your declaration of variable 'p' allocates only enough space on your stack for a single (int *) pointer, but then you stuff values into (&p + 2), etc. so you end up overwriting who-knows-what. It behaves differently with or without gdb because the who-knows-what part just might not be critical in one environment but is critical in the other.

You might be able to "fix" your program by making sure that the space you're about to trash isn't anything critical.

int main(){
 int* p;
 char junk[100];    /* ADD THIS */

Now, the space following the storage allocated for 'p' will (most likely) be the junk char array, which you can get away with overwriting. (At least that "fixes" the program on my particular Linux system, when I compile with "gcc -O0 -g").

All that said -- the method you're using there is not in any way portable or safe. The compiler makes no promise that its going to arrange the storage allocations in the particular order that we declare them. Also, compiling with different optimization switches may change the behavior. So while this might be an interesting exercise, you should certainly not expect this sort of method to work consistently.

Manually manipulating the C stack this way is a BAD IDEA!



来源:https://stackoverflow.com/questions/4177996/return-to-libc-works-in-gdb-but-not-when-running-alone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!