Friday 15 August 2014

SublimeText Build System for nasm (assembly)

Just been playing looking at the SecurityTube Linux Assembly course (again) and decided to use SublimeText as the editor for writing the code.

Got frustrated with having to type the compile and link each time at the command line and was pretty sure you could configure SublimeText to do this for you rather than use a bash script.

After a quick read of the sublime docs I found the following would work:

 {
"cmd": ["nasm -f elf32 ${file} -o ${file_path}/${file_base_name}.o && ld -o ${file_path}/${file_base_name} ${file_path}/${file_base_name}.o"],
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "shell": true
}

To add to sublime go to Tools > Build System > New Build System, copy and paste all the text above over the top of what already exists, then save as nasm. Set the Build System to nasm and then use ctrl+b or F7 to build.

Wednesday 29 January 2014

Sniffing iOS traffic using remote virtual interface...

Today I learned something new =)

It is possible to sniff the traffic from an iOS device without the need for a proxy or jailbreak!

If you have a mac there is a command "rvictl" that allows you to capture any traffic for an attached mobile device.

Simply attach a device via the USB cable and run the command rvictl with -s to start the capture and the udid of the device attached.

rvictl -s <udid> 


This will create a virtual interface:


You can now use tcpdump or wireshark to capture the traffic.


 sudo tcpdump -i rvi0 -n -vv



Handy little trick for troubleshooting and sniffing traffic that I didn't know existed. I think it will only capture WiFi traffic, I haven't played to see if it will grab mobile network traffic.

Every day's a skool day!

Thursday 23 January 2014

class-dump-z armv7 & armv7s

I recently tried to class dump from an iPhone application that was running on an iPhone5s (7.0.4). After firing up class-dump-z and running, nothing seemed to happen, class-dump-z just hung.



Wondering if this was something to do with 64bit and the iPhone5s I decided to run lipo on the binary to check it out:


lipo -info Prometheus


Hmm, armv7 & armv7s. Had a look at the help options on class-dump-z and noticed that there was an option to select the architecture using -u. I tried the following:

class-dump-z -u armv7 Prometheus



class-dump-z -u armv7s Prometheus



Aagain, nothing.

Next option was to extract armv7 & armv7s from the binary using lipo as below:

lipo Prometheus -extract armv7 -output Prometheus-armv7

lipo Prometheus -extract armv7s -output Prometheus-armv7s



I then ran class-dump-z against each, for some reason the armv7 binary didn't dump...



But armv7s did which was enough for now, why it doesn't work using the -u option I'm not sure...

Monday 13 January 2014

Get lucky... #CES2014 iBeacon Scavenger Hunt


Last week the consumer electronics show (CES2014) was on in Las Vegas. A lot of new tech was on show from 4k ultra hd TVs to e-ciggs! To accompany the show an iPhone app was released to help delegates find stands, each other, talks and panel discussions. As well as all this a scavenger hunt was built into the app using the new iBeacon technology available iOS7. The purpose of the hunt was to find each the beacons located around the show, when you are in range of a beacon you get notified and then the beacon is marked as found in the application. First to find all the beacons gets a prize.... W00t! 



As I have been looking into blue tooth low energy and iBeacons for a customer I decided to reverse the application and see if I could "find" all the beacons from the comfort of my seat :)

So what is an iBeacon?

The Apple web site describes them as….

"iBeacon is a new technology that extends Location Services in iOS. Your iOS device can alert apps when you approach or leave a location with an iBeacon. In addition to monitoring location, an app can estimate your proximity to an iBeacon (for example, a display or checkout counter in a retail store). Instead of using latitude and longitude to define the location, iBeacon uses a Bluetooth low energy signal, which iOS devices detect. To learn more about Bluetooth technology, see the official Bluetooth website."

Basically an iBeacon is a BTLE chip that is emitting a UUID, a major location, and a minor location. You end up having something like:

UUID: 3D481CE6-DAC4-48E1-AA8C-8BACD8C24557
Major: 1
Minor: 65001


This is broadcast and the iOS application is scanning for the UUID, you can also include the major if this is not likely to change. When they are found by the application it does something, e.g. calculate proximity let the user know they are close by or have just left the area. A better technical write up is available hereAlso the Apple developer documentation is available here.

There is a lot of hype starting to surround them and that seems to have gained since CES2014, I guess many of the journalists at the event saw the scavenger hunt. (See links below).

http://www.cultofmac.com/261988/apples-ibeacon-hyped/

http://9to5mac.com/2014/01/02/ces-2014-to-host-ibeacon-scavenger-hunt-w-official-mobile-apps/

http://blogs.computerworld.com/ios/23344/apple-ibeacon-tech-lights-ces-2014 

How was I going to win the competition without moving to far?

I installed the CES application on my jailbroken iPhone and had a nose around. I used libimobiledevice  to start pulling back the syslog to my laptop, you can also do this using the iPhone configuration utility too. I prefer idevicesyslog in libimobiledevice a it doesn’t jump around so much on the terminal when you are looking at the console/log.

When I fired the application up and started the scavenger hunt I noticed what looked like the UUID and some minor numbers:

Now I had these all I needed to find was the Major and I could spoof beacons.

I ssh’d onto the device and located the application, dumped it and decrypted it using clutch. Clutch is a favourite of crackers but also very handy for hackers / pen testers to dump and application to be read in IDApro, hopper, class-dump-z or whatever. I ran strings on the binary, which showed up a few references to beacon and UUID but nothing to concrete. No major found here.

I continued to look around the sub directories of the application and found a few SQLite databases which looked promising, the names of the tables sounded like they would hold the details of iBeacons that were found. I looked inside each of the tables but again, nothing.

I then found a plist that looked like a default preferences file which had some interesting stuff in it and some reference to sh_targets. I assumed this was scavenger hunt targets. The data inside the key sh_target_list was all hex: 


I grabbed it and chucked it into a hex 2 ASCII converter available on the internets... Hmm looked a lot like a binary plist. 


I copied the hex from the original plist into a file and converted from hex into a binary file using xxd as below:

xxd -r -p ces.hex ces.plist

I could now convert this into xml using plutil

plutil -convert xml1 ces.plist

Now I had a plist I could look at in Xcode or any other text editor. Once opened, it was easy to see the dev had embedded the details of a found beacon inside the plist and also the minor id’s, which matched up with what I had found in the log. 

This left me with two options, I keep looking for the major and spoof each beacon or I see if I can set the individual beacons to found = YES in the plist.

After hunting around a little bit longer for the major I decided the quickest route to success would be by trying to set the found key to = YES.

To get everything back into the right order I would need to do the following:


  • Edit the plist with the keys ‘found' and ‘i_beacon_minor' in and set the found key to YES
  • Use plutil to convert the plist back to binary
  • Grab a hex dump of the modified plist and copy hex back into the default preferences plist.
  • Convert the default preferences plist back to binary and then copy over to my device and replace the old file.

Set key value to true:




Convert back to binary plist:

plutil -convert binary ces.plist

I then used hexfiend to dump the hex, I guess I could of used hex dump or xxd but hexfeind forted the hex nicely and didn’t grab the offset when doing cut and paste:

Once pasted into the default preferences post I now had all I needed to win.


I SCP'd it over to the device and fired up the application… WINNER


I’m not sure what would have happened if I had tried to claim the prize remotely? I’m guessing that they may have had some metrics that could have identified how quickly I found each beacon, making it physically impossible to have visited each beacon individually. However with some further digging I‘m sure I could have found the major ID and spoofed each beacon with a raspberry Pi or another iOS device. Setting some reasonable times between each it could have been believable.... A free 4K UHD curved TV would have been good =D

If you are planning to use iBeacons for prizes or some kind of promotion code then I would suggest you use a web server backend with reasonable protection to stop this kind of hack, it wasn’t that hard and could be done pretty quickly. 

If you believe the hype iBeacons have a big future, it will be interesting to see the implementations and how people secure them properly.

Friday 3 January 2014

Decrypting iOS Kernel Cache (A4 CPU Devices)

Decrypting the iOS kernel cache on devices with an A4 or lower CPU is relatively straight forward thanks to the limera1n boot exploit. This allows the extraction of the IV & Keys for each file within the IPSW software bundle which are published on the iPhone Wiki. Each time new firmware package is released the keys are updated.

I believe it is possible to dump the kernel cache from a device with an A5 and greater chip but so far I haven't played with this. This has to be done from memory rather than extracting from the IPSW which is more complex.

To decrypt your kernel  you first need to download a copy of the IPSW package for your device, I'm going to use the iPhone 4 GSM 7.0.4 firmware available here:


Once the firmware has downloaded you can simply unzip the IPSW file and extract the contents, you should have the following:



The file you are interested in is kernelcache.release.xx. In this instance, the file we want is kernelcache.release.n90. n90 is specific device identifier for the iPhone 4, each device will have it's own identifier. If you are using an iPad or iPod then the identifier here will be different.


The kernel is an img3 format file that is encrypted and also compressed using lzss so we need to decrypt it then decompress it.

To decrypt you can use either xpwn or decodeimg3, I opted for decodeimg3 as it was a single perl script! You can download decodeimg3 from here:

http://nah6.com/~itsme/cvs-xdadevtools/iphone/tools/decodeimg3.pl

I had a couple of issues running the script first off as I didn't have "Crypt::Rijndael" perl module installed (info on installing perl modules here). Once this was installed it worked fine.

To decrypt the kernelcache you will also need the IV and Key from the iPhone wiki for the specific firmware build you are interested in. The iPhone 4 GSM IV & Key can be found here:

http://theiphonewiki.com/wiki/InnsbruckTaos_11B554a_(iPhone_4_GSM)

Once you are on that page locate the IV & Key for kernelcache.release.n90 as below, you will need them in a minute:


To decrypt your extracted kernel use the following command:

$ ./decodeimg3 <YOUR KERNEL> -v -o <DECRYPTED KERNEL> -k <KEY FROM WIKI> -iv <IV FROM WIKI> 
  • <YOUR KERNEL> = kernelcache.release.n90 we extracted from IPSW earlier.
  • -v = Verbose
  • -o = Output file, I use the same file name and append .lzss as it is easy to see it's lzss for decompressing.
  • -k = Key from wiki
  • -iv = IV from wiki


Below is the output from decrypting the kernel:



Next step is to decompress the kernel using lzssdec, the source code can be found here:


You will need to compile this, I used the following command to compile it on OSX:

$ g++ lzssdec.cpp -o lzssdec

Now you need to know the offset at where the lzss section starts. Opening the decrypted and uncompressed kernel in a hex editor and looking for 0xFEEDFACE should show you the offset. The screen shot below shows this:


The offset we need is 0x0180 to decompress our kernelcache.release.n90.lzss file.

Using the lzssdec tool we compiled earlier, the correct offset and our decrypted kernel, we can now decompress to give us a mach-0 arm binary using the command below: 

$ lzssdec -o 0x0180 < kernelcache.release.n90.lzss > kernelcache.release.n90.cleartext


To check you have a decrypted and decompressed mach-o ARM binary use the following:

$ file kernelcache.release.n90.cleartext 


 The binary should open up in IDAPro or Hopper so you can disassemble and reverse the kernel further :)

Thanks...
  1.  Willem Hengeveld for his scripts and tools (decodeimg3 & lzssdec).
  2. Jonathan Levin for the book OSX & iOS Internals, an excellent reference.
  3. The iPhoneWiki, best iOS resource on the www! 

Tuesday 5 November 2013

OpenJailbreak, fuzzyDuck & iOS fuzzing...

OpenJailbreak Project:-


At JailbreakCon 2013 in new york the launch of a new project "OpenJailbreak" was announced. The main purpose of OpenJailbreak is to create a central open source repository for all jailbreaking tools that are created when a Jailbreak release is developed. This should give developers, security researchers and Jailbreak teams the tools they need to keep jailbreaking sustainable for the future. At the moment there are a handful of projects running but as the initiative picks up more and more side projects are expected to flourish.

As well as creating the the tools and providing the source, another stream has come from the OpenJailbreak project in the form of education and training. Each and every week a Jailbreak class is run. The goal of the project is for the class to create an untethered jailbreak from the members of the community that contribute to the classes each week. The class is held via Skype & IRC each Saturday at 1pm UTC and usually last around an 1-2 hours.

Each week progress is discussed with individual members contributing their findings and passing on their knowledge to the group. So far this has been tools, crashes or anything they have found that is of interest to jailbreaking in general.

The initial classes discussed the jailbreaking process and what will be required. Since then things have begun to pick up speed and time has been spent looking into fuzzing and creating various tools and wrappers that can automate the fuzzing process. The next step is to investigate the crashes that have been submitted and try to reverse engineer what is happening. Once this done it maybe possible find out if the crash is vulnerable and can be used for an exploit. More information on the classes can be found at the links below:

http://www.reddit.com/r/jailbreak/comments/1nxoq7/openjailbreak_class/

fuzzyDuck automated iOS fuzzing tool:-


As fuzzing was topical I thought I would take a look into it and read the chapter on fuzzing from the iOS hackers handbook. After reading this and listening into some of the discussion on #OpenJailbreak I decided to look into automating the process so that a test case could be fuzzed, tested with MobileSafari and then any crash copied to a directory for later review along with the fuzzed test case. I could then check it out  and ensure it was reproducible across platforms and iOS versions.

Web Server

I decided that the best way to do this was probably going to be on the device, the downside of this is you need a Jailbroken device but it does provide you plenty of flexibility in copying the crash.plist and the test case to where you want in order to investigate further. A couple of people were looking at using python as a web server on the device which seemed feasible as you could simply use:


#python -m SimpleHTTPServer 8080

This would create a web server from the directory your in, you can then serve up the test case and run it via MobilSsafari. e.g. simply opening:

http://localhost:8080/myTestCase.mov

After trying this I found that python wasn't the best option, it was causing the .mov file to not play in MobilSafari. Serving the same content to normal desktop Safari from the device was fine and the .mov files seemed to play ok. I don't know why this was happening but decided to look for another httpd daemon to serve up the test cases on the device. It didn't take long to find lighttpd which is a very light weight http server (as the name suggests) and is available from cydia.

When I started the lighttpd daemon this and tried to access a .mov file I had created using the camera on the device it played perfectly via MobileSafari on device. Cool, I grabbed another mov from the Apple Support site and tried to spin that up using lighttpd and MobileSafari on device. This didn't play in mobile safari but did on desktop safari... which I *think* was important. I noticed that if you have a mov file you are going to fuzz it should probably play before it is fuzzed. This isn't necessarily the gospel (just my findings), but if the .mov file your testing with is failing to play before it gets to the interesting bit in the file you have fuzzed, then your fuzzing is going to be useless. I think it is probably safe to say if the mov file plays then it is a good candidate to fuzz with and you will have more chance of crashing.

Fuzzer

Now I had a webserver I needed to create a script that would run, mutating my test case and then launching it in Mobile Safari. If it caused a crash then the crash dump and the mutated test case should be copied to a crashes directory. This is pretty much how the iOS Hackers Handbook does it so I thought I would give it a go. In the book Charlie Miller is using python to write his own fuzzer. After not having much luck with python earlier and reading that it had performance issues running on iOS I thought it would be better to use zzuf. Zzuf had been discussed in the classes and a few others were having luck with it so gave it a go. I'm not sure where it came from but I managed to find a copy of a zzuf that had been built for iOS. I believe it was compiled for ARM by comex so props to him for that!

zzuff takes the original test case mutates it and then outputs it to another file. As well as giving it the input file and output file you can specify a seed and ratio for mutation. The ratio I am using in my script was suggested by compiledEntropy, but if you need to you can play with this and change it around to see what results you get, the more you mess with it the longer it may take to generate a test case. This is the command I use to create test cases:

#zzuf -s $RANDOM -r 0.0001:0.001 < originalTestCase.mov > mutatedTestCase.mov

Testing

After the test case is created I needed a way to test it, iOS Hackers Handbook to the rescue (again)! The simplest way to test this is using a tool called sbopenurl. Simply passing it a URL it will fire MobileSafari and inject the URL to it. This tool is available from the cydia package com.innoying.sbutils. The command is simply:

#sbopenurl http://localhost:3000/mutatedTestCase.mov

I know others had tried to create web pages that auto ran the test case but this seemed to fail. Mobile Safari seems to demand input from the user before playing so it wouldn't work in an automated fashion.

Crash Dumps

Now I had a way to serve the test cases (lighttpd), create the test cases (zzuf) and open the test cases (sbopenurl). The final step was to check for crashes and put it into one big loop to run and run! It seems that nearly all test crashes eventually end up in:


/var/mobile/Library/Logs/CrashReporter/

I'm not entirely sure how they get there though, it seems after a Kernel Panic the kernel panic logs are initially created in the directory below:

/var/logs/CrashReporter/

When you navigate to Settings > General > About > Diagnostics & Usage > Diagnostics & Usage Data  on the device the crash logs are copied into the directory previously mentioned:

/var/mobile/Library/Logs/CrashReporter/

I couldn't work out what was doing this, I looked through the preferences app and there seems to be an instance method cleanupTimer that is invoking crash_mover. I tried to run crash_mover manually and by starting the launch daemon (com.apple.crash_mover) but this didn't work. In the end I gave up and decided to just check both directories for logs and copy them out. I would have preferred to aggregate them all in one directory using an 'OEM' supplied method like crash_mover but this will have to do for now.

Recovering

After running my script for a few days I soon realised that I was getting kernel panic, which was good but it meant that my testing stopped until I manually started the script again. I wanted to test all day & night, just checking the results at the end of the day. This wasn't going to be too difficult as I could simply create a launch daemon to run on reboot. The xml below created the launch daemon and it is then installed via fuzzyDuck tool:



House Keeping and Install

I wanted fuzzyDuck to be easy for anyone to use, so it also includes a number of steps to check for required software and install if necessary as well as some fairly verbose output. I think overall it is a fairly useful tool for a beginner to play with. To get fuzzy duck grab it from the github link below:

https://github.com/isa56k/fuzzyDuck

The readme.MD contains the instructions on how to install. Any questions fire them over on twitter or IRC to @isa56k =)

Now to try understand WTF the crash dumps are telling me.... 

Monday 9 September 2013

Swerving 'Root' detection on Android...

Last week I was having problems with an Android application that had root detection built in. I don't do a great deal with Android so it's not something I have had to look at before. A user at work had 'rooted' their device to tweak it a little and disable a load of 'bloatware' which was apparently causing performance issues.

Once they had rooted it one of their key applications stopped working as it appeared to be doing some 'root' detection, having looked at iOS jailbreak detection and defeated that for some apps I decided to have a crack and see if something similar could be done. I have played around with Android Debugging Bridge (adb) before so already had the Android SDK installed.

First up was grabbing a copy of the .apk from the device, this was pretty easy as I could list the apps via adb shell and then use adb pull to copy the .apk across to my laptop. Simples.

$ adb shell
shell@mako:/ $ pm list packages -f | grep <name of application>
$ adb pull <path to .apk>


Once I had a copy of the .apk I just needed to decompile it to work out what was going on. A quick google and I found 'apktool'. I installed it and then ran against the .apk which generated a load of directories and crucially some smali code. Smali is an assembler/disassembler for the dex format used by davlik (Android), more info on it here https://code.google.com/p/smali/.

To disassemble the application it was pretty easy, no decrypting 'FairPlay' like you see on iOS:

$ apktool d <path to .apk>


A quick grep of the .smali files for the keyword 'rooted' and I was able to find all the files that might be related to the root detection, this was a bit of guess work but I got lucky! I was soon able to find a couple of methods called 'isRootedDevice' and 'isRooted' in a couple of the smali files. Had the developers called the method something else it might not have been quite so easy. 

$grep -ri rooted

This looked promising so I opened each smali file and searched for 'isRooted'. 

From examining the code I worked out that the developers were looking for the file /system/app/Superuser.apk and also something called 'test-keys'.


I googled what Superuser.apk is and found a few posts on StackOverflow and the following blog:

http://www.simonroses.com/2013/06/appsec-build-rooted-detection-in-your-app/

It seems Superuser.apk is used to manage what applications have su (root) access. It would make sense for the developer to check for this as I guess it is used on most rooted devices (a bit like cydia). If I could change the .apk file that the app was looking for I might be able to defeat this step. The other item that is being checked is 'Test-Keys', apparently this is a generic key for signing packages.

I modified the smali code so that the application would only report it was rooted if it found a random apk or string. As these would never be found the device would not report that it was rooted.


Next I used the apktool to recompile the binary:

$ apktool b <directory with source smali in>


Now I had a package, I could install it onto my device using adb. I tried to install but got the error 'Failure [INSTALL_PARSE_FAILED_NO_CERTIFICATES]':


It seems I need to sign the package before Android will let me install it. A bit of 'Google Power' and I found that you need to sign the package with javasigner. First of all I would need a certificate so I created a key store and cert with key tool  and then signed as below:

keytool -genkey -v -keystore testing.keystore -alias testing -keyalg RSA -keysize 2048 -validity 10000

$ jarsigner -verbose -keystore testing.keystore -digestalg SHA1 -sigalg MD5withRSA <path to apk> testing


Once this was done I installed on a rooted device and bingo... no prompt to say the device was rooted!


I was surprised how easy this was, I had expected it to be a little more challenging. It's quite easy to see how simple it would be to modify a binary add a trojan or some malware and then distribute.