482 views
# cs6332: Unit5 static binary rewriting (115 points + bonus 30 points) In continuation of Lab 4, which focused on implementing a dynamic binary translator, we now move on to building a static binary rewriter using the [e9patch framework][e9patch], which employs a trampoline-based binary rewriting technique as described in the [E9Patch paper][e9patch paper]. For this unit, we have prepared three exploitable binaries drawn from past challenges: *(1)* [a buffer-overflow vulnerability][bof], *(2)* [a shellcode exercise][shellcode], and *(3)* [a ROP challenge][rop]. We also provide accompanying pwntools scripts (e.g., `ex.py`) to launch attacks against these binaries. All essential resources for this unit are available in the [User Guide] and [Programming Guide]. You may also refer to the [tutorial page][tutorial] for example uses of the e9patch framework in patching and instrumenting binaries. The Unit 5 materials can be downloaded from [here][unit5]. You can also copy `/home/labs/unit5.zip` inside ctf-vm2. :::info The unit will be due on *11:59 PM, Dec 3, 2026*. ::: The lab consists of three core parts, along with a bonus task, as described below. --- ## Part 1: Instruction Counting (30 points) Extend the example template on the [tutorial page][tutorial] to build a static binary rewriter that reports two counts in `output.txt`: 1. **Executed instructions.** Count each execution of an original instruction in the main executable. 2. **Executed memory-access instructions.** Count each execution of an original instruction in the main executable that reads or writes data memory. Include implicit stack accesses, such as those made by `call` and `ret`. Count a read-modify-write instruction once. An instruction such as `lea`, which computes an address without accessing memory, does not count toward this total. Exclude instructions added by instrumentation and instructions executed in shared libraries or the dynamic loader from both totals. ### Instrumentation requirement For the total instruction count, use probes that each account for a group of original instructions. For example, you can add a basic block's static instruction count each time that block executes. Placing a probe at every instruction is disallowed for this total. Dense instrumentation can cause E9Patch's patching tactics to interfere with one another. See Section 5.2 (limitation L3) of the [E9Patch paper][e9patch paper]. In your `README.md`, explain where you place probes, how many instructions each probe accounts for, and why your method counts the executed paths correctly when a branch is taken or a loop repeats. ### Validation and submission 1. Run your rewriter on the validation binary with both inputs specified in the handout. For each run, record the expected and observed values for both counts in your `README.md`. 2. Run your rewriter on `bof-level03` with the benign input `Yes` and include the resulting `output.txt`. 3. Submit `part1.sh`, any required instrumentation source, and your `README.md`. Include the commands needed to reproduce your results on a course VM. ```shell $ ./a.out This is a 64-bit program. The 1st argument will be passed via rdi, the 2nd will be passed via rsi, the 3rd will be passed via rdx, the 4th will be pased via rcx, etc.. Values in two local variables are: a = 0x4141414141414141 b = 0x4242424242424242 Can you change these values to: a = 0x6867666564636261 and b = 0x4847464544434241? Type YES if you agree with this... (a fake message, you may overflow the input buffer). Yes Now the variables store: a = 0x4040404040404040 b = 0x4444444444444444 Analyze the program! # Output is directed to "output.txt". $ cat output.txt ================================================== Executed instructions: 123456789 Executed memory-access instructions: 9876543 ================================================== ``` :::warning For the *all-instruction counting* task, please avoid instrumenting the analysis routine on **every single instruction**. One drawback of trampoline-based static binary rewriting is that patching tactics can interfere with one another. If you attempt to patch all (or nearly all) instructions, these interdependencies may cause conflicts and reduce the overall applicability of the rewriter. You can refer to Section 5.2 (limitation L3) of the [E9Patch paper][e9patch paper] for a detailed explanation. ::: ## Part 2: Shadow Stack (40 points) In this part, as in previous assignments, you are asked to instrument call and ret instructions to establish a shadow stack. You may reuse your earlier implementations (e.g., ShadowStacks Lab 3 and Lab 4) to complete this component. :::warning Unlike dynamic binary instrumentation, a static binary rewriter does not have control over code from dependent libraries. In other words, if your binary calls printf() from the libc library, you do not have permission to rewrite that function. Please ensure that your shadow stack still functions correctly despite this limited coverage. It should not kill the process for benign inputs, yet it must still prevent control-flow hijacking attacks. ::: ## Part 3: Patching Binaries (45 points) Many control-hijacking attacks arise from programmer mistakes. For instance, in the bof-level03 example, the bug resides in the *receive_input()* function due to a mismatch between the size of the allocated buffer (line 3) and the amount of data read from user input (*fgets()* function in line 14). This bug could be fixed by either (1) increasing the size of the allocated buffer or (2) reducing the number of bytes read. ```c= void receive_input() { uint64_t a = 0x4141414141414141, b = 0x4242424242424242; char buf[20]; printf("This is a 64-bit program.\n"); printf("The 1st argument will be passed via rdi, the 2nd will be passed via rsi,\nthe 3rd will be passed via rdx, the 4th will be pased via rcx, etc..\n"); printf("Values in two local variables are:\n" "a = 0x%016lx b = 0x%016lx\n", a, b); printf("Can you change these values to:\n" "a = 0x6867666564636261 and b = 0x4847464544434241?\n"); printf("Type YES if you agree with this... (a fake message, you may overflow the input buffer).\n"); fgets(buf, 64, stdin); a -= 0x0101010101010101; b += 0x0202020202020202; printf("Now the variables store:\n" "a = 0x%016lx b = 0x%016lx\n", a, b); uint64_t *ret_val = buf + 56; if(a == 0x6867666564636261 && b == 0x4847464544434241) { printf("Great, but I will not execute get_a_shell() for you..\n"); printf("Run it yourself!\n"); if(&get_a_shell != *ret_val) { exit(-1); } for(int i = 0; i < 8; i++) { buf[56+i] = buf[i]; } } else { printf("Analyze the program!\n"); exit(-1); } } ``` Assuming we are given only the binaries, without access to the original source code, please patch the three provided binaries to eliminate the bug and prevent exploitation in a postmortem manner. ## Part 4 (Bonus): Remediate Heartbleed vulnerability (30 points) In this part, you are given only an OpenSSL binary that urgently needs to be patched for the famous [Heartbleed vulnerability][Heartbleed]. Again, we assume that you do not have access to the binary’s source code. You are provided with the vulnerable OpenSSL binary and its exploit script. This binary was built from [commit 0d7717f][0d7717f], which is the immediate predecessor of the official [Heartbleed commit] ([Heartbleed patch]). The commit patches two functions—*dtls1_process_heartbeat(SSL \*s)* and *tls1_process_heartbeat(SSL \*s)*—across two source files. It will be a fun exercise to think about how you can apply this patch at the binary level to counter the famous Heartbleed attack without interfering with the original semantics of the OpenSSL binary. ### How to reproduce Heartbleed attack The following steps describe how to reproduce the Heartbleed proof-of-concept using the provided `openssl` binary. You will first run the TLS/SSL web server, and then launch the attack against it. Please note that you must choose and specify **a port number** for the PoC. Using a port that is already in use by other users may cause conflicts. You may select any available port in the range *1024–65535*. #### 1. Running openssl server ```bash # Getting into the challenge directory $ cd testcases/heartbleed # specify the server port to listen $ export PORT=4433 # Generate self-signed (-x509) private/public key pairs --- key.pem and cert.pem $ ./openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes -subj "/C=US/ST=NC/L=Chapel Hill/O=Acme/CN=www.example.com" # Run SSL/TLS server $ ./openssl s_server -key key.pem -cert cert.pem -accept $PORT -www ``` #### 2. Lauch the attack ```bash # specify the server port to connect. $ export PORT=4433 $ ./post.sh username password Simulating login with username=username and password=password $ python3 exploit.py [Connecting to localhost port 4433] username=username&password=password [Closing socket] ``` ## Submission guideline Please organize your submission using the directory structure shown in the assignment. Each subdirectory should contain all materials relevant to that part, including a short summary in README.md, the driver script you used (for example, partX.sh), and the trampoline source file required for instrumentation (such as partX.c). This structure ensures that each component of your work is self-contained and easy to evaluate. ``` $ tree unit5-kxj190011 unit5-kxj190011 ├── part1 │   ├── part1.c │   ├── part1.sh │   └── README.md ├── part2 │   ├── part2.c │   ├── part2.sh │   └── README.md ├── part3 │   ├── part3.c │   ├── part3.sh │   └── README.md ├── part4 │   ├── part4.c │   ├── part4.sh │   └── README.md └── README.md ``` ###### tags: `cs6332`,`lab5`,`e9patch` --- [tutorial]:https://codimd.syssec.org/s/ZY71YEBHW [e9patch]:https://github.com/GJDuck/e9patch [e9patch paper]:https://www.comp.nus.edu.sg/~gregory/papers/e9patch.pdf [Heartbleed]:https://www.heartbleed.com/ [0d7717f]:https://github.com/openssl/openssl/commit/0d7717fc9c83dafab8153cbd5e2180e6e04cc802 [HeartBleed commit]:https://github.com/openssl/openssl/commit/96db9023b881d7cd9f379b0c154650d6c108e9a3 [HeartBleed patch]:https://cs6332.syssec.org/l/week12/res/heartbleed.patch.txt [User guide]:https://github.com/GJDuck/e9patch/blob/master/doc/e9tool-user-guide.md [Programming guide]:https://github.com/GJDuck/e9patch/blob/master/doc/e9patch-programming-guide.md [unit5]:https://gitlab.syssec.org/kjee/unit5-static-binary-rewriter/-/releases [bof]:https://gitlab.syssec.org/kjee/unit5-static-binary-rewriter/-/tree/main/testcases/bof-level03?ref_type=heads [shellcode]:https://gitlab.syssec.org/kjee/unit5-static-binary-rewriter/-/tree/main/testcases/21-stack-ovfl-sc-64?ref_type=heads [rop]:https://gitlab.syssec.org/kjee/unit5-static-binary-rewriter/-/tree/main/testcases/rop-1-64?ref_type=heads