26.07.2018 Views

hacking-the-art-of-exploitation

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

pointer.c<br />

#include <br />

#include <br />

int main() {<br />

char str_a[20]; // A 20-element character array<br />

char *pointer; // A pointer, meant for a character array<br />

char *pointer2; // And yet ano<strong>the</strong>r one<br />

strcpy(str_a, "Hello, world!\n");<br />

pointer = str_a; // Set <strong>the</strong> first pointer to <strong>the</strong> st<strong>art</strong> <strong>of</strong> <strong>the</strong> array.<br />

printf(pointer);<br />

}<br />

pointer2 = pointer + 2; // Set <strong>the</strong> second one 2 bytes fur<strong>the</strong>r in.<br />

printf(pointer2); // Print it.<br />

strcpy(pointer2, "y you guys!\n"); // Copy into that spot.<br />

printf(pointer); // Print again.<br />

As <strong>the</strong> comments in <strong>the</strong> code indicate, <strong>the</strong> first pointer is set at <strong>the</strong> beginning<br />

<strong>of</strong> <strong>the</strong> character array. When <strong>the</strong> character array is referenced like this,<br />

it is actually a pointer itself. This is how this buffer was passed as a pointer to<br />

<strong>the</strong> printf() and strcpy() functions earlier. The second pointer is set to <strong>the</strong><br />

first pointer’s address plus two, and <strong>the</strong>n some things are printed (shown in<br />

<strong>the</strong> output below).<br />

reader@<strong>hacking</strong>:~/booksrc $ gcc -o pointer pointer.c<br />

reader@<strong>hacking</strong>:~/booksrc $ ./pointer<br />

Hello, world!<br />

llo, world!<br />

Hey you guys!<br />

reader@<strong>hacking</strong>:~/booksrc $<br />

Let’s take a look at this with GDB. The program is recompiled, and a<br />

breakpoint is set on <strong>the</strong> tenth line <strong>of</strong> <strong>the</strong> source code. This will stop <strong>the</strong><br />

program after <strong>the</strong> "Hello, world!\n" string has been copied into <strong>the</strong> str_a<br />

buffer and <strong>the</strong> pointer variable is set to <strong>the</strong> beginning <strong>of</strong> it.<br />

reader@<strong>hacking</strong>:~/booksrc $ gcc -g -o pointer pointer.c<br />

reader@<strong>hacking</strong>:~/booksrc $ gdb -q ./pointer<br />

Using host libthread_db library "/lib/tls/i686/cmov/libthread_db.so.1".<br />

(gdb) list<br />

1 #include <br />

2 #include <br />

3<br />

4 int main() {<br />

5 char str_a[20]; // A 20-element character array<br />

6 char *pointer; // A pointer, meant for a character array<br />

44 0x200

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!