embedded devices security firmware reverse...

104
Embedded Devices Security Firmware Reverse Engineering Jonas Zaddach Andrei Costin August 11, 2013 Andrei Costin/Jonas Zaddach www.rmware.re 1/104

Upload: hoangngoc

Post on 25-Apr-2018

239 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Embedded Devices SecurityFirmware Reverse Engineering

Jonas Zaddach Andrei Costin

August 11 2013

Andrei CostinJonas Zaddach wwwfirmwarere 1104

About ndash Jonas Zaddach

bull PhD candidate on Development of novelbinary analysis techniques for securityapplications at EURECOM

bull Advised by Prof Davide Balzarottibull Co-founder of FIRMWAREREbull Previous works hard-disks rdquotorturerrdquo

Amazon EC2 securitybull jonasfirmwarerebull jonaszaddacheurecomfr

Andrei CostinJonas Zaddach wwwfirmwarere 2104

About ndash Andrei Costin

bull PhD candidate on Software security inembedded systems at EURECOM

bull Advised by Prof Aureacutelien Francillonbull Co-founder of FIRMWAREREbull Author of MFCUK (Mifare Classic)

BT5-RFID (RFID-focused livecd)bull Previous works printers ADS-Bbull andreifirmwarerebull andreicostineurecomfr

Andrei CostinJonas Zaddach wwwfirmwarere 3104

Administratrivia ndash Legal

bull Please fill-in the BH13US Feedback Form - Thanksbull The views of the authors are their own and do not

represent the position of their employers or research labsbull By following the entire or part of this workshop you agree

bull to use the tools and knowledge acquired only for legalpurposes and for activities you have explicit authorization for

bull to waive off presenters any liability which might arise fromapplying the tools or knowledge acquired by the attendee

bull to contribute at the best of attendee capability back to thesecurity research community in terms of knowledge toolsand experience

Andrei CostinJonas Zaddach wwwfirmwarere 4104

Administratrivia ndash Setup

Before we actually start - get the exercise instructions and startdownloading the tools image to have it ready

bull Follow instructions at httpfirmwarerebh13usphpbull Or connect to WIFI

bull SSID firmwarere_bh13usbull KEY firmwarere_bh13us_380154bull Follow instructions at

ftpanonymous19216811sda_part1bh13ushtml

Andrei CostinJonas Zaddach wwwfirmwarere 5104

Eurecom ndash About

Academic Partners

Andrei CostinJonas Zaddach wwwfirmwarere 6104

Eurecom ndash About

Industrial Partners

Andrei CostinJonas Zaddach wwwfirmwarere 7104

Eurecom ndash Cote drsquoAzur

Andrei CostinJonas Zaddach wwwfirmwarere 8104

About ndash FIRMWAREREInstead of relaxing at the beach we are working to bring you

FIRMWARERE

Andrei CostinJonas Zaddach wwwfirmwarere 9104

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 2: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

About ndash Jonas Zaddach

bull PhD candidate on Development of novelbinary analysis techniques for securityapplications at EURECOM

bull Advised by Prof Davide Balzarottibull Co-founder of FIRMWAREREbull Previous works hard-disks rdquotorturerrdquo

Amazon EC2 securitybull jonasfirmwarerebull jonaszaddacheurecomfr

Andrei CostinJonas Zaddach wwwfirmwarere 2104

About ndash Andrei Costin

bull PhD candidate on Software security inembedded systems at EURECOM

bull Advised by Prof Aureacutelien Francillonbull Co-founder of FIRMWAREREbull Author of MFCUK (Mifare Classic)

BT5-RFID (RFID-focused livecd)bull Previous works printers ADS-Bbull andreifirmwarerebull andreicostineurecomfr

Andrei CostinJonas Zaddach wwwfirmwarere 3104

Administratrivia ndash Legal

bull Please fill-in the BH13US Feedback Form - Thanksbull The views of the authors are their own and do not

represent the position of their employers or research labsbull By following the entire or part of this workshop you agree

bull to use the tools and knowledge acquired only for legalpurposes and for activities you have explicit authorization for

bull to waive off presenters any liability which might arise fromapplying the tools or knowledge acquired by the attendee

bull to contribute at the best of attendee capability back to thesecurity research community in terms of knowledge toolsand experience

Andrei CostinJonas Zaddach wwwfirmwarere 4104

Administratrivia ndash Setup

Before we actually start - get the exercise instructions and startdownloading the tools image to have it ready

bull Follow instructions at httpfirmwarerebh13usphpbull Or connect to WIFI

bull SSID firmwarere_bh13usbull KEY firmwarere_bh13us_380154bull Follow instructions at

ftpanonymous19216811sda_part1bh13ushtml

Andrei CostinJonas Zaddach wwwfirmwarere 5104

Eurecom ndash About

Academic Partners

Andrei CostinJonas Zaddach wwwfirmwarere 6104

Eurecom ndash About

Industrial Partners

Andrei CostinJonas Zaddach wwwfirmwarere 7104

Eurecom ndash Cote drsquoAzur

Andrei CostinJonas Zaddach wwwfirmwarere 8104

About ndash FIRMWAREREInstead of relaxing at the beach we are working to bring you

FIRMWARERE

Andrei CostinJonas Zaddach wwwfirmwarere 9104

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 3: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

About ndash Andrei Costin

bull PhD candidate on Software security inembedded systems at EURECOM

bull Advised by Prof Aureacutelien Francillonbull Co-founder of FIRMWAREREbull Author of MFCUK (Mifare Classic)

BT5-RFID (RFID-focused livecd)bull Previous works printers ADS-Bbull andreifirmwarerebull andreicostineurecomfr

Andrei CostinJonas Zaddach wwwfirmwarere 3104

Administratrivia ndash Legal

bull Please fill-in the BH13US Feedback Form - Thanksbull The views of the authors are their own and do not

represent the position of their employers or research labsbull By following the entire or part of this workshop you agree

bull to use the tools and knowledge acquired only for legalpurposes and for activities you have explicit authorization for

bull to waive off presenters any liability which might arise fromapplying the tools or knowledge acquired by the attendee

bull to contribute at the best of attendee capability back to thesecurity research community in terms of knowledge toolsand experience

Andrei CostinJonas Zaddach wwwfirmwarere 4104

Administratrivia ndash Setup

Before we actually start - get the exercise instructions and startdownloading the tools image to have it ready

bull Follow instructions at httpfirmwarerebh13usphpbull Or connect to WIFI

bull SSID firmwarere_bh13usbull KEY firmwarere_bh13us_380154bull Follow instructions at

ftpanonymous19216811sda_part1bh13ushtml

Andrei CostinJonas Zaddach wwwfirmwarere 5104

Eurecom ndash About

Academic Partners

Andrei CostinJonas Zaddach wwwfirmwarere 6104

Eurecom ndash About

Industrial Partners

Andrei CostinJonas Zaddach wwwfirmwarere 7104

Eurecom ndash Cote drsquoAzur

Andrei CostinJonas Zaddach wwwfirmwarere 8104

About ndash FIRMWAREREInstead of relaxing at the beach we are working to bring you

FIRMWARERE

Andrei CostinJonas Zaddach wwwfirmwarere 9104

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 4: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Administratrivia ndash Legal

bull Please fill-in the BH13US Feedback Form - Thanksbull The views of the authors are their own and do not

represent the position of their employers or research labsbull By following the entire or part of this workshop you agree

bull to use the tools and knowledge acquired only for legalpurposes and for activities you have explicit authorization for

bull to waive off presenters any liability which might arise fromapplying the tools or knowledge acquired by the attendee

bull to contribute at the best of attendee capability back to thesecurity research community in terms of knowledge toolsand experience

Andrei CostinJonas Zaddach wwwfirmwarere 4104

Administratrivia ndash Setup

Before we actually start - get the exercise instructions and startdownloading the tools image to have it ready

bull Follow instructions at httpfirmwarerebh13usphpbull Or connect to WIFI

bull SSID firmwarere_bh13usbull KEY firmwarere_bh13us_380154bull Follow instructions at

ftpanonymous19216811sda_part1bh13ushtml

Andrei CostinJonas Zaddach wwwfirmwarere 5104

Eurecom ndash About

Academic Partners

Andrei CostinJonas Zaddach wwwfirmwarere 6104

Eurecom ndash About

Industrial Partners

Andrei CostinJonas Zaddach wwwfirmwarere 7104

Eurecom ndash Cote drsquoAzur

Andrei CostinJonas Zaddach wwwfirmwarere 8104

About ndash FIRMWAREREInstead of relaxing at the beach we are working to bring you

FIRMWARERE

Andrei CostinJonas Zaddach wwwfirmwarere 9104

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 5: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Administratrivia ndash Setup

Before we actually start - get the exercise instructions and startdownloading the tools image to have it ready

bull Follow instructions at httpfirmwarerebh13usphpbull Or connect to WIFI

bull SSID firmwarere_bh13usbull KEY firmwarere_bh13us_380154bull Follow instructions at

ftpanonymous19216811sda_part1bh13ushtml

Andrei CostinJonas Zaddach wwwfirmwarere 5104

Eurecom ndash About

Academic Partners

Andrei CostinJonas Zaddach wwwfirmwarere 6104

Eurecom ndash About

Industrial Partners

Andrei CostinJonas Zaddach wwwfirmwarere 7104

Eurecom ndash Cote drsquoAzur

Andrei CostinJonas Zaddach wwwfirmwarere 8104

About ndash FIRMWAREREInstead of relaxing at the beach we are working to bring you

FIRMWARERE

Andrei CostinJonas Zaddach wwwfirmwarere 9104

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 6: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Eurecom ndash About

Academic Partners

Andrei CostinJonas Zaddach wwwfirmwarere 6104

Eurecom ndash About

Industrial Partners

Andrei CostinJonas Zaddach wwwfirmwarere 7104

Eurecom ndash Cote drsquoAzur

Andrei CostinJonas Zaddach wwwfirmwarere 8104

About ndash FIRMWAREREInstead of relaxing at the beach we are working to bring you

FIRMWARERE

Andrei CostinJonas Zaddach wwwfirmwarere 9104

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 7: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Eurecom ndash About

Industrial Partners

Andrei CostinJonas Zaddach wwwfirmwarere 7104

Eurecom ndash Cote drsquoAzur

Andrei CostinJonas Zaddach wwwfirmwarere 8104

About ndash FIRMWAREREInstead of relaxing at the beach we are working to bring you

FIRMWARERE

Andrei CostinJonas Zaddach wwwfirmwarere 9104

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 8: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Eurecom ndash Cote drsquoAzur

Andrei CostinJonas Zaddach wwwfirmwarere 8104

About ndash FIRMWAREREInstead of relaxing at the beach we are working to bring you

FIRMWARERE

Andrei CostinJonas Zaddach wwwfirmwarere 9104

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 9: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

About ndash FIRMWAREREInstead of relaxing at the beach we are working to bring you

FIRMWARERE

Andrei CostinJonas Zaddach wwwfirmwarere 9104

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 10: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Introduction

Introduction

Andrei CostinJonas Zaddach wwwfirmwarere 10104

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 11: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Workshop Roadmap

bull 1st part (1415 ndash 1515)bull Little bit of theorybull Overview of state of the artbull Warm-up exercises

bull 2nd part (1530 ndash 1630)bull Encountered formats toolsbull Unpacking challenges and ideasbull Analysis and plugin-dev exercises

bull 3rd part (1700 ndash 1800)bull Emulation introductionbull Awesome exercises ndash letrsquos have some real fun

Andrei CostinJonas Zaddach wwwfirmwarere 11104

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 12: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

What is a Firmware (Ascher Opler)

bull Ascher Opler coined the term firmware in a 1967Datamation article

bull Currently in short itrsquos the set of software that makes anembedded system functional

Andrei CostinJonas Zaddach wwwfirmwarere 12104

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 13: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

What is firmware (IEEE)

bull IEEE Standard Glossary of Software EngineeringTerminology Std 61012-1990 defines firmware as follows

bull The combination of a hardware device and computerinstructions and data that reside as read-only software onthat device

bull Notes (1) This term is sometimes used to refer only to thehardware device or only to the computer instructions ordata but these meanings are deprecated

bull Notes (2) The confusion surrounding this term has ledsome to suggest that it be avoided altogether

Andrei CostinJonas Zaddach wwwfirmwarere 13104

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 14: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Common Embedded Device Classes

bull Networking ndash Routers Switches NAS VoIP phonesbull Surveillance ndash Alarms Cameras CCTV DVRs NVRsbull Industry Automation ndash PLCs Power Plants Industrial

Process Monitoring and Automationbull Home Automation ndash Sensoring Smart Homes Z-Waves

Philips Huebull Whiteware ndash Washing Machine Fridge Dryerbull Entertainment gear ndash TV DVRs Receiver Stereo Game

Console MP3 Player Camera Mobile Phone Toysbull Other Devices - Hard Drives Printersbull Carsbull Medical Devices

Andrei CostinJonas Zaddach wwwfirmwarere 14104

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 15: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

In the news - Home Routers

bull 2012-04-26 The Hacker News More than 100000Wireless Routers have Default Backdoor [3 7]

bull Arcadyan Speedport routers allow connection with WPSbackdoor PIN (even when WPS is disabled)

bull 2013-03-15 Slashdot Backdoor found in TP-Linkrouters [15 16]

bull HTTP request triggers download and execution of a TFTPfile as root

bull CSRF attack leads to denial of servicebull 2013-04-17 CNET Top Wi-Fi routers easy to hack says

study [9 10]bull Flaws allow access without authenticationbull Management sessions can be hijacked

Andrei CostinJonas Zaddach wwwfirmwarere 15104

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 16: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

In the news - Professional Routers

bull 2010-03-02 Forbes Ciscorsquos Backdoor ForHackers [17 2]

bull Lawful interception interface prone to abusebull 2013-03-15 Full-Disclosure Critical SSH Backdoor in

multiple Barracuda Networks Products [11]bull System contains backdoor user accounts that cannot be

removedbull IP access to SSH is whitelisted for Barracuda Networks and

others

Andrei CostinJonas Zaddach wwwfirmwarere 16104

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 17: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

In the news - Medical Devices

bull 2008 Pacemakers and Implantable CardiacDefibrillators Software Radio Attacks and Zero-PowerDefenses [19]

bull Radio protocol discloses sensitive informationbull Operations of an ICD can be reprogrammed without

authorizationbull 2011-08-05 Dark Reading Getting Root On The Human

Body [4 21 6]bull Radio protocol of insuline pump is not securebull Injection programs can be changed

Andrei CostinJonas Zaddach wwwfirmwarere 17104

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 18: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware in the news - SCADA

bull How digital detectives deciphered Stuxnet the mostmenacing malware in history - July 2010 [18 5]

bull Stuxnet was a targeted attack against the Natanz uraniumenrichment facility

bull An infected computer would send commands to exactly thethere-used centrifuges that would drive them out of theirspecification range

bull The lessons of Shamoon and Stuxnet ignored US ICSstill vulnerable in the same way - 2013-01-04 [13]

bull Attacks on SCADA systems are increasing -2013-07-03 [8 12]

bull Number of SQL injection attacks spear phishing etcagainst utility increased

Andrei CostinJonas Zaddach wwwfirmwarere 18104

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 19: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware in the news - Cellphones

bull Kaspersky Researchers Discover Most AdvancedAndroid Malware Yet - June 2013 [23 22]

bull The threat from this particular malware is low butbull Sophistication of Android malware is about to reach the

same level as computersbull Millions of Sim cards are rsquovulnerable to hack attackrsquo -

July 2013 [14 1]bull An implementation flaw in many older SIM cards makes it

possible to break the manufacturer key used to signsoftware updates - stay tuned for the talk here on BH

Andrei CostinJonas Zaddach wwwfirmwarere 19104

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 20: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Common Processor Architectures

LOW ENDbull MSP430bull 8051bull Atmel AVR

HIGH ENDbull ARM (ARM7 ARM9

Cortex)bull Intel ATOMbull MIPSbull Motorola 680068000 (68k)bull Ambarellabull Axis CRISbull TensilicaXtensa

Andrei CostinJonas Zaddach wwwfirmwarere 20104

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 21: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Common Buses

bull Serial buses - SPI I2C 1-Wire UARTbull PCI PCIExpressbull AMBA

Andrei CostinJonas Zaddach wwwfirmwarere 21104

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 22: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Common Communication Lines

bull Ethernet - RJ45bull RS485bull CANFlexRaybull Bluetoothbull WIFIbull Infraredbull Zigbeebull Other radios (ISM-Band etc)bull GPRSUMTSbull USB

Andrei CostinJonas Zaddach wwwfirmwarere 22104

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 23: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Common Directly AddressableMemory

bull DRAMbull SRAMbull ROMbull Memory-Mapped NOR Flash

Andrei CostinJonas Zaddach wwwfirmwarere 23104

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 24: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Common Storage

bull NAND Flashbull SD Cardbull Hard Drive

Andrei CostinJonas Zaddach wwwfirmwarere 24104

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 25: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Common Operating Systems

bull Linuxbull Perhaps most favourite and most encoutered

bull VxWorksbull Cisco IOSbull Windows CENTbull L4bull eCosbull DOSbull Symbianbull JunOSbull Ambarellabull etc

Andrei CostinJonas Zaddach wwwfirmwarere 25104

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 26: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Common Bootloaders

bull U-Bootbull Perhaps most favourite and most encoutered

bull RedBootbull BareBoxbull Ubicom bootloaderbull OpenFirmware

Andrei CostinJonas Zaddach wwwfirmwarere 26104

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 27: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Common Libraries and Dev Envs

bull busybox + uClibcbull Perhaps most favourite and most encoutered

bull buildrootbull openembeddedbull crosstoolbull crossdev

rArr At the end of the build process the vendor (or we) obtain aflashable firmware image including bootloader operatingsystem and applications

Andrei CostinJonas Zaddach wwwfirmwarere 27104

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 28: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

First unpacking exercise

bull IQeye Smart Camera Systems ndash IQeye 832 V345Firmware

bull Alinking IP Camera Systems ndash Alinking CMOS Mega PixelBox IP Cam ALC 9153

Andrei CostinJonas Zaddach wwwfirmwarere 28104

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 29: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

What Challenges Do FirmwaresBring

bull Non-standard formatsbull Encrypted chunksbull Non-standard or non-accessible update channels

bull Firmwares come and go vendors quickly withdraw themfrom supportftp sites

bull Industry standard update channels like ADSL with ACSbull Non-standard update procedures

bull Printerrsquos updates via vendor-specific PJL hacksbull Gazillion of other hacks

bull Firmware update file not available at allbull Firmware only distributed on devicersquos flashbull Needs to be dumped from the flash for analysis

Andrei CostinJonas Zaddach wwwfirmwarere 29104

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 30: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Updating to a New Firmware

bull Firmware Update built-in functionalitybull Web-based uploadbull Socket-based uploadbull USB-based upload

bull Firmware Update function in the bootloaderbull USB-boot recoverybull Rescue partition eg

bull New firmware is written to a safe space andintegrity-checked before it is activated

bull Old firmware is not overwritten before new one is active

bull JTAGISPParallel programming

Andrei CostinJonas Zaddach wwwfirmwarere 30104

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 31: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Updating to a New Firmware ndash Pitfalls

bull TOCTTOU attacks [20]bull Non-mutual-authenticating update protocolsbull Non-signed packagesbull Non-verified signaturesbull Incorrectlyinconsistently verified signaturesbull Leaking signature keys

Andrei CostinJonas Zaddach wwwfirmwarere 31104

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 32: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Why Are Most Firmwares Outdated

Vendor-viewbull Profit and fast time-to-market first

bull Support and security comes (if at all) as an after-thought

bull Great platform variety raises compilation and maintenanceeffort

bull Verification process is cumbersome takes a lot of time andeffort

bull Eg for medical devices depends on national standardswhich require strict verification procedure sometimes evenby the state

Andrei CostinJonas Zaddach wwwfirmwarere 32104

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 33: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Why Are Most Firmwares Outdated

Customer-viewbull rdquoIf it works donrsquot touch itrdquobull High effort for customers to install firmwaresbull High probability something goes wrong during firmware

upgradesrarr Some devices do not provide recovery procedures incase something goes wrong (Bricking)

bull rdquoWhere do I put this upgrade CD into a printer ndash it has nokeyboard nor a monitor nor an optical driverdquo

Andrei CostinJonas Zaddach wwwfirmwarere 33104

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 34: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

1st Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 34104

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 35: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Formats

Firmware Formats

Andrei CostinJonas Zaddach wwwfirmwarere 35104

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 36: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Formats ndash Typical ObjectsInside

bull Bootloader (1st2nd stage)bull Kernelbull File-system imagesbull User-land binariesbull Resources and support filesbull Web-serverweb-interface

Andrei CostinJonas Zaddach wwwfirmwarere 36104

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 37: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Formats ndash ComponentsCategory View

bull Full-blownbull full-OSkernel + bootloader + libs + apps

bull Integratedbull apps + OS-as-a-lib

bull Partial updatesbull apps or libs or resources or support

Andrei CostinJonas Zaddach wwwfirmwarere 37104

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 38: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Formats ndash PackingCategory View I

bull Pure filesystemsbull YAFFSbull JFFS2bull SquashFSbull CramFSbull ROMFSbull UbiFSbull xFATbull NTFSbull extNfs

Andrei CostinJonas Zaddach wwwfirmwarere 38104

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 39: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Formats ndash PackingCategory View II

bull Pure archivesbull CPIObull Arbull Tarbull GZipbull Bzip2bull LZxxxbull RPMDEB

bull Pure binary formatsbull iHEXbull SRECS19

bull Hybrids (any breed of above)

Andrei CostinJonas Zaddach wwwfirmwarere 39104

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 40: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Analysis

Firmware Analysis

Andrei CostinJonas Zaddach wwwfirmwarere 40104

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 41: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Analysis ndash Overview

bull Reconnaissance first ndash when done on devicebull Get the firmware then Reconnaissance ndash when only

firmware is availablebull Unpackingbull Reuse engineering (check codegooglecom and

sourceforgenet)bull Localize point of interest

bull password cracking ndash etcpasswdbull web pentesting ndash varwww etclighttpd

bull Decompilecompiletweakfuzzpentestfun

Andrei CostinJonas Zaddach wwwfirmwarere 41104

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 42: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Analysis ndash Getting theFirmware

Many times not as easy as it sounds In order of increasingcomplexity of getting the firmware image

bull Present on the product CDDVDbull Download from manufacturer FTPHTTP sitebull Many times need to register for manufacturer spam (bull Google Dorksbull FTP index sites (mmntnet ftpfilesnet)bull Wireshark traces (manufacturer firmware download tool or

device communication itself)bull Device memory dump

Andrei CostinJonas Zaddach wwwfirmwarere 42104

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 43: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Analysis ndash Reconnaissance

bull strings on the firmware imageblobbull Fuzzy string matching on a wide embedded product DB

bull Find and read the specs and datasheets of devicebull Google

Andrei CostinJonas Zaddach wwwfirmwarere 43104

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 44: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Analysis ndash Unpacking

bull Did anyone pay attention to the previous section

Andrei CostinJonas Zaddach wwwfirmwarere 44104

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 45: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Unpacking firmware from SRECiHEXfiles

SREC and iHEX are much simpler binary file formats than elf -in a nutshell they just store memory addresses and data(Altough it is possible to specify more information it is optionaland in most cases missing)Those files can be transformed to elf with the commandobjcopy -I ihex -O elf32-little ltinputgt ltoutputgtobjcopy -I srec -O elf32-little ltinputgt ltoutputgt

Of course information like processor architecture entry pointand symbols are still missing as they are not part of the originalfiles You will later see some tricks how to guess thatinformation

Andrei CostinJonas Zaddach wwwfirmwarere 45104

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 46: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Emulation

Firmware Emulation

Andrei CostinJonas Zaddach wwwfirmwarere 46104

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 47: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Emulation ndash Prerequisites

bull Self-built kernel image with a superset of kernel modulesbull The devicersquos kernel is normally not usable since all device

addresses are hardcoded (unlike in the x86 architecture)bull The kernel serves as abstraction layer for hardware present

in the emulator compile your own and userspace programsstill work

bull QEMU compiled with embedded device CPU support (egARM MIPS)

bull Firmware ndash most usually split into smaller partsFS-imageswhich do not break QEMU

Andrei CostinJonas Zaddach wwwfirmwarere 47104

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 48: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Debugging Embedded Systems

bull JTAG Proprietary debugging connectionbull Software debugger (eg GDB stub or ARM Angel Debug

monitor) connected pex over UARTbull OS debug capabilities (eg KDBKGDB)

Andrei CostinJonas Zaddach wwwfirmwarere 48104

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 49: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Developing for Embedded Systems

bull GCCBinutils toolchainbull Cross-compilersbull Proprietary compilerbull Building the image

Andrei CostinJonas Zaddach wwwfirmwarere 49104

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 50: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Firmware Exercise

Firmware Exercise

Andrei CostinJonas Zaddach wwwfirmwarere 50104

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 51: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Reversing a Seagate HDDrsquos firmwarefile format

Taskbull Obtain the firmware imagebull Extract the firmware filebull Reverse-engineer the firmware file format

Andrei CostinJonas Zaddach wwwfirmwarere 51104

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 52: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Obtaining the firmware

Andrei CostinJonas Zaddach wwwfirmwarere 52104

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 53: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Unpacking the firmware

A quite stupid and boring mechanic task

$ 7z x MooseDT-MX1A-3D4D-DMax22iso -oisoimage$ cd isoimage$ ls[BOOT] DriveDetectexe FreeDOS READMEtxt$ cd [BOOT]$ lsBootable_144Mimg$ file Bootable_144MimgBootable_144Mimg DOS floppy 1440kx86 hard disk boot sector

Andrei CostinJonas Zaddach wwwfirmwarere 53104

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 54: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Unpacking the firmware

$ mkdir -p mnt2imgimage$ mount -o loop Bootable_144Mimg mnt2imgimage$ mkdir imgimage$ cp -r mnt2imgimage imgimage$ cd disk$ lsAUTOEXECBAT COMMANDCOM CONFIGSYS HIMEMEXEKERNELSYS MX1A3D4DZIP RDISKEXE TDSKEXEunzipexe$ mkdir archive$ cd archive$ unzip MX1A3D4DZIP$ ls6_8hmx1atxs CHOICEEXE FDAPMCOM fdl464exeflashbat LISTCOM MX1A4dlod READMETXTseaenumexe

Andrei CostinJonas Zaddach wwwfirmwarere 54104

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 55: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Unpacking the firmware

$ file 6_8hmx1atxs ASCII text with CRLF line terminatorsCHOICEEXE MS-DOS executable MZ for MS-DOSFDAPMCOM FREE-DOS executable (COM) UPX compressedfdl464exe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressedflashbat DOS batch file ASCII text with CRLF

line terminatorsLISTCOM DOS executable (COM)MX1A4dlod dataREADMETXT ASCII English text with CRLF line

terminatorsseaenumexe MS-DOS executable COFF for MS-DOS

DJGPP go32 DOS extender UPX compressed

Andrei CostinJonas Zaddach wwwfirmwarere 55104

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 56: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Unpacking the firmware

$ less flashbatset exe=fdl464exeset family=Mooseset model1=MAXTOR STM3750330ASset model2=MAXTOR STM31000340ASrem set model3=rem set firmware=MX1A4dloddset cfgfile=6_8hmx1atxsset options=-s -x -b -v -a 20SEAFLASH1exe -m family options -h cfgfileif errorlevel 2 goto WRONGMODEL1if errorlevel 1 goto ERRORgoto DONE

Andrei CostinJonas Zaddach wwwfirmwarere 56104

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 57: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Unpacking the firmware (Summary) I

bull We have unpacked the various wrappers layers archivesand filesystems of the firmware

bull ISO rarr DOS IMG rarr ZIP rarr LOD

bull The firmware is flashed on the HDD in a DOS environment(FreeDOS)

bull The update is run by executing a DOS batch file (flashbat)bull There are

bull a firmware flash tool (fdl464exe)bull a configuration for that tool (6_8hmx1atxs encrypted or

obfuscatedencoded)bull the actual firmware (MX1A4dlod)

Andrei CostinJonas Zaddach wwwfirmwarere 57104

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 58: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Unpacking the firmware (Summary) II

bull The firmware file is not in a binary format known to file andmagic tools

bull Sample heuristic to identify files of interestbull Unpack the firmwarebull Group by their magicbull Flag for inspection the ones of interest or those with

magic == data

rarr Letrsquos have a look at the firmware file

Andrei CostinJonas Zaddach wwwfirmwarere 58104

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 59: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Inspecting the firmware file hexdump

$ hexdump -C MX1A4dlod00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 ||00000010 80 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||00000020 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 00 ||00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 79 dc |y|00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ||000001c0 0e 10 14 13 02 00 03 10 00 00 00 00 ff 10 41 00 |A|000001d0 00 20 00 00 ad 03 2d 00 13 11 15 16 11 13 07 20 | - |000001e0 00 00 00 00 40 20 00 00 00 00 00 00 00 00 00 00 | |000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3f 1d ||00000200 00 c0 49 00 00 00 2d 00 10 b5 27 48 40 68 41 42 |I-rsquoHhAB|00000210 26 48 00 f0 78 ee 10 bd 10 b5 04 1c ff f7 f4 ff |ampHx|00000220 a0 42 03 d2 22 49 40 18 00 1b 10 bd 00 1b 10 bd |BI|00000230 1d 48 40 68 40 42 70 47 10 b5 01 1c ff f7 f8 ff |HhBpG|00000240 41 1a 0f 20 00 f0 5e ee 10 bd 7c b5 04 1c 20 1c |A ˆ| |00000250 00 21 00 90 17 a0 01 91 0c c8 00 98 00 f0 f2 ed ||00000260 01 da 00 f0 ed ff ff f7 cf ff 05 1c 28 1c ff f7 |(|00000270 d3 ff a0 42 fa d3 7c bd 7c b5 04 1c 20 01 00 1b |B|| |00000280 00 21 00 90 0b a0 01 91 0c c8 00 98 00 f0 da ed ||

rarr The header did not look familiar to me (

Andrei CostinJonas Zaddach wwwfirmwarere 59104

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 60: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Inspecting the firmware file strings

$ strings MX1A4dlodXlatePhySec h[Sec][NumSecs]XlatePhySec p[Sec][NumSecs]XlatePlpChs d[Cyl][Hd][Sec][NumSecs]XlatePlpChw f[Cyl][Hd][Wdg][NumWdgs]XlateSfi D[PhyCyl][Hd][Sfi][NumSfis]XlateWedge t[Wdg][NumWdgs]ChannelTemperatureAdj U[TweakTemperature][Partition][Hd][Zone][Opts]WrChs W[Sec][NumSecs][PhyOpt][Opts]EnableDisableWrFault u[Op]WrLba W[Lba][NumLbas][Opts]WrLongOrSystemChs w[LongSec][LongSecsOrSysSec][SysSecs][LongPhySecOpt][SysOpts]RwPowerAsicReg V[RegAddr][RegValue][WrOpt]WrPeripheralReg s[OpType][RegAddr][RegValue][RegMask][RegPagAddr]WrPeripheralReg t[OpType][RegAddr][RegValue][RegMask][RegPagAddr]

rarr Strings are visible meaning the program is neither encryptednor compressed

Andrei CostinJonas Zaddach wwwfirmwarere 60104

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 61: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Inspecting the firmware file binwalk

$ binwalk MX1A4dlod

DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------499792 0x7A050 Zip archive data compressed size 48028

uncompressed size 785886 name

$ dd if=MX1A4dlod of=tmpblabin bs=1 skip=499792$ unzip -l tmpblabinArchive tmpblabin

End-of-central-directory signature not found Either this file is nota zipfile or it constitutes one disk of a multi-part archive In thelatter case the central directory and zipfile comment will be found onthe last disk(s) of this archive

unzip cannot find zipfile directory in one of tmpblabin ortmpblabinzip and cannot find tmpblabinZIP period

rarr binwalk does not know this firmware the contained archivewas apparently a false positive

Andrei CostinJonas Zaddach wwwfirmwarere 61104

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 62: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Inspecting the firmware fileVisualization

To spot different sections in a binary file a visual representationcan be helpful

bull HexWorkshop is a commercial program for Windows Mostcomplete featureset (Hex editor visualisation )httpwwwhexworkshopcom

bull Binvis is a project on google code for different binaryvisualisation methods Visualisation is ok but the programseems unfinished httpcodegooglecompbinvis

bull Bin2bmp is a very simple python script that computes abitmap from your binaryhttpsourceforgenetprojectsbin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 62104

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 63: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Inspecting the firmware fileVisualization with bin2bmp

Andrei CostinJonas Zaddach wwwfirmwarere 63104

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 64: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Identifying the CPU instruction set

bull ARM Look out for bytes in the form of 0xeX that occurevery 4th byte The highest nibble of the instruction word inARM is the condition field whose value 0xe means ALexecute this instruction unconditionally The instructionspace is populated sparsely so a disassembly will quicklyend in an invalid instruction or lots of conditionalinstructions

bull Thumb Look out for words with the pattern 0xF000F000(blblx) 0xB500BD00 (pop XXX pc followed by pushXXX lr) 0x4770 (bx lr) The Thumb instruction set ismuch denser than the ARM instruction set so adisassembly will go for a long time before hitting an invalidinstruction

Andrei CostinJonas Zaddach wwwfirmwarere 64104

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 65: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Identifying the CPU instruction set

bull i386bull x86_64bull MIPS

In general you should either know the processor already fromthe reconnaissance phase or you try to disassemble parts ofthe file with a disassembler for the processor you suspect thecode was compiled for In the visual representation executablecode should be mostly colorful (dense instruction sets) ordisplay patterns (sparse instruction sets)

Andrei CostinJonas Zaddach wwwfirmwarere 65104

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 66: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Identifying the CPU instruction set

In our firmware searching for rdquoerdquo in the hexdump leads us to00002420 04 e0 4e e2 00 40 2d e9 00 e0 4f e1 00 50 2d e9 |N-OP-|00002430 db f0 21 e3 8f 5f 2d e9 18 10 9f e5 00 00 91 e5 |_-|00002440 30 ff 2f e1 8f 5f bd e8 d1 f0 21 e3 00 50 bd e8 |0_P|00002450 0e f0 69 e1 00 80 fd e8 44 00 00 00 08 20 fe 01 |iD |00002460 94 00 00 00 00 30 a0 e1 0c ce 9f e5 01 00 a0 e1 |0|00002470 10 40 2d e9 14 10 93 e5 be c3 dc e1 d0 10 d1 e1 |-|00002480 08 e0 93 e5 02 20 8c e0 92 01 01 e0 20 c0 e0 e3 | |00002490 81 22 61 e0 01 25 62 e0 42 29 a0 e1 82 0c 62 e1 |abB)b|000024a0 d8 cd 9f e5 82 11 81 e0 c6 20 51 e2 42 20 81 42 | QB B|000024b0 81 10 8c e0 f0 10 d1 e1 82 20 8c e0 04 c0 93 e5 | |000024c0 f0 20 d2 e1 ac 01 2c e1 8e c2 2c e1 00 c0 83 e5 | |000024d0 ac cd 9f e5 fc c9 dc e1 00 00 5c e3 10 40 bd a8 ||000024e0 8e 1a 04 aa 10 80 bd e8 f0 41 2d e9 94 7d 9f e5 |A-|000024f0 80 40 a0 e1 07 00 54 e3 00 50 a0 e1 f7 6f 47 e2 |TPoG|

Letrsquos verify that this is indeed ARM code

Andrei CostinJonas Zaddach wwwfirmwarere 66104

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 67: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Finding the CPU instruction set$ dd if=MX1A4dlod bs=1 skip=$(( 0x2420 )) gt tmpblabin$ arm-none-eabi-objdump -b binary -m arm -D tmpblabin

tmpblabin file format binary

Disassembly of section data

00000000 ltdatagt0 e24ee004 sub lr lr 44 e92d4000 stmfd sp lr8 e14fe000 mrs lr SPSRc e92d5000 push ip lr10 e321f0db msr CPSR_c 219 0xdb14 e92d5f8f push r0 r1 r2 r3 r7 r8 r9 sl fp ip lr18 e59f1018 ldr r1 [pc 24] 0x381c e5910000 ldr r0 [r1]20 e12fff30 blx r024 e8bd5f8f pop r0 r1 r2 r3 r7 r8 r9 sl fp ip lr28 e321f0d1 msr CPSR_c 209 0xd12c e8bd5000 pop ip lr30 e169f00e msr SPSR_fc lr34 e8fd8000 ldm sp pcˆ38 00000044 andeq r0 r0 r4 asr 323c 01fe2008 mvnseq r2 r840 00000094 muleq r0 r4 r044 e1a03000 mov r3 r048 e59fce0c ldr ip [pc 3596] 0xe5c

rarr Looks goodAndrei CostinJonas Zaddach wwwfirmwarere 67104

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 68: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Navigating the firmware

At the very beginning of a firmware the stack needs to be setup for each CPU mode This typically happens in a sequence ofmsr CPSR_c XXX instructions which switch the CPU modeand assignments to the stack pointer The msr instruction existsonly in ARM mode (not true for Thumb2 any more ( ) Veryclose you should also find some coprocessor initializations(mrcmcr)

18a2c e3a000d7 mov r0 215 0xd718a30 e121f000 msr CPSR_c r018a34 e59fd0cc ldr sp [pc 204] 0x18b0818a38 e3a000d3 mov r0 211 0xd318a3c e121f000 msr CPSR_c r018a40 e59fd0c4 ldr sp [pc 196] 0x18b0c18a44 ee071f9a mcr 15 0 r1 cr7 cr10 418a48 e3a00806 mov r0 393216 0x6000018a4c ee3f1f11 mrc 15 1 r1 cr15 cr1 018a50 e1801001 orr r1 r0 r118a54 ee2f1f11 mcr 15 1 r1 cr15 cr1 0

Andrei CostinJonas Zaddach wwwfirmwarere 68104

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 69: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Navigating the firmware

In the ARMv5 architecture exceptions are handled by ARMinstructions in a table at address 0 Normally these have theform ldr pc XXX and load the program counter with a valuestored relative to the current program counter (ie in a tablefrom address 0x20 on)rarr The exception vectors give an idea of which addresses areused by the firmwarearm-none-eabi-objdump -b binary -m arm -D MX1A4dlod

| grep -E rsquoldrs+pcrsquo | less

Andrei CostinJonas Zaddach wwwfirmwarere 69104

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 70: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Navigating the firmware

rarr We get the following output from arm-none-eabi-objdump220e4 e59ff018 ldr pc [pc 24] 0x22104220e8 e59ff018 ldr pc [pc 24] 0x22108220ec e59ff018 ldr pc [pc 24] 0x2210c220f0 e59ff018 ldr pc [pc 24] 0x22110220f4 e59ff018 ldr pc [pc 24] 0x22114220f8 e1a00000 nop (mov r0 r0)220fc e59ff018 ldr pc [pc 24] 0x2211c22100 e59ff018 ldr pc [pc 24] 0x2212022104 0000a824 andeq sl r0 r4 lsr 1622108 0000a8a4 andeq sl r0 r4 lsr 172210c 0000a828 andeq sl r0 r8 lsr 1622110 0000a7ec andeq sl r0 ip ror 1522114 0000a44c andeq sl r0 ip asr 822118 00000000 andeq r0 r0 r02211c 0000a6ac andeq sl r0 ip lsr 1322120 00000058 andeq r0 r0 r8 asr r0

Andrei CostinJonas Zaddach wwwfirmwarere 70104

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 71: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Seagate firmware ndash take-aways

bull Firmware unpacking takes a large amount of time and trialand error

bull Unpacking can be automated to spend more of your timewith actual code analysis which is where you shouldspend your time

bull How See the next exercise

Andrei CostinJonas Zaddach wwwfirmwarere 71104

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 72: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Seagate firmware ndash BAT plugins

bull In this exercise we are going to develop two plugins thatwill allow BAT to unpack the Seagate firmware into singlefiles

bull An ISO unpacking plugin that extracts files from a CD imagebull A Dos Floppy Image (FAT16 formatted) extractor plugin

Andrei CostinJonas Zaddach wwwfirmwarere 72104

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 73: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Adding the ISO plugin to the BATconfiguration file

bull Add this to rsquotoolsgpltoolsrcbruteforce-configrsquo after the unpack scans block

As we have seen gpltoolbat by default doesnrsquot unpack thersquo[BOOT]rsquo section of an ISO Letrsquos write our ISO unpacker for this

[iso9660_7z]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackISO7zpriority = 3magic = iso9660noscan = textxmlgraphicspdfcompressedaudiovideojavadescription = Unpack ISO9660 (CD-ROM) file systems using 7zenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 73104

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 74: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Adding the IMG plugin to the BATconfiguration file

As we have seen gpltoolbat by default doesnrsquot recognize rsquoDOS floppy imagersquo img file Letrsquos write our IMG unpacker for this

[dosfloppy]type = unpackmodule = batfirmware_re_bh13usmethod = searchUnpackDosFloppyImgpriority = 2description = Unpack FAT16 DOS floppy img filesenabled = yes

Andrei CostinJonas Zaddach wwwfirmwarere 74104

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 75: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Writing the ISO plugin to the BATconfiguration file

bull Edit rsquotoolsgpltoolsrcbatfirmware_re_bh13uspyrsquobull Add implementation for the ISO unpackerbull Using the 7z -x ltisofilegt -oltoutput_dirgt

command that we saw beforeimport subprocessimport osimport shutilimport magic

def searchUnpackISO7z(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpack

Andrei CostinJonas Zaddach wwwfirmwarere 75104

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 76: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Writing the ISO plugin to the BATconfiguration file

tmpdir = fwunpackdirsetup(tempdir filenameiso-7z counter)

cmd = [rsquo7zrsquo rsquoxrsquo filename rsquo-osrsquo (tmpdir ) ]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPE close_fds=True)(stanout stanerr) = pcommunicate()

if preturncode = 0shutilrmtree(tmpdir)

elsetagsappend(rsquoisorsquo)diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 76104

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 77: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Writing the IMG plugin to the BATconfiguration file

bull The same for the IMG unpacker pluginbull Using the mcopy -i ltimgfilegt -s -p -m -n -oltoutput_dirgt command

def searchUnpackDosFloppyImg(filename tempdir=None blacklist=[]offsets= envvars=None)

tags = []counter = 1diroffsets = []

Reuse from BATimport fwunpacktmpdir = fwunpackdirsetup(tempdir filename

dosfloppy counter)cmd = [rsquomcopyrsquo rsquo-irsquo filename rsquo-srsquo rsquo-prsquo

rsquo-mrsquo rsquo-nrsquo rsquorsquo tmpdir]p = subprocessPopen(cmd stdout=subprocessPIPE

stderr=subprocessPIPEclose_fds=True)

Andrei CostinJonas Zaddach wwwfirmwarere 77104

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 78: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Writing the IMG plugin to the BATconfiguration file

(stanout stanerr) = pcommunicate()if preturncode = 0

shutilrmtree(tmpdir)else

tagsappend(rsquodosrsquo)

ms = magicopen(magicMAGIC_NONE)msload()mstype = msfile(filename)msclose()

if mstype = None and rsquobootrsquo in mstypetagsappend(rsquobootrsquo)

diroffsetsappend((tmpdir 0 osstat(filename)st_size))blacklistappend((0 osstat(filename)st_size))

return (diroffsets blacklist tags)

Andrei CostinJonas Zaddach wwwfirmwarere 78104

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 79: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Seagate firmware unpacking withBAT ndash take-aways

bull We were able to automate all the unpacking by adding twoplugins to BAT

bull For future similar firmwares we do not need to do any workany more

Andrei CostinJonas Zaddach wwwfirmwarere 79104

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 80: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

2nd Break

bull Please be back in 10 minutes

Andrei CostinJonas Zaddach wwwfirmwarere 80104

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 81: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Emulating a Linux-based firmwareSamsung Network HD Box Camerafirmware exercise

The goal is to run the firmware of a Samsung Network HD BoxCamera (SNB7000) with as much functionality as possible in asystem emulator (Qemu)

Andrei CostinJonas Zaddach wwwfirmwarere 81104

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 82: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Emulating a Linux-based firmware

bull We need a new Linux kernel Whybull Because the existing one is not compiled for the peripherals

emulated by Qemu and will fail due to non-existent devices

Andrei CostinJonas Zaddach wwwfirmwarere 82104

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 83: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Compiling a Linux kernel for Qemu

Following this tutorial to build the kernelhttpxecdesigncomcompiling-a-kernelsudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf ia32-libsgit clone httpsgithubcomraspberrypilinuxgitwget httpxecdesigncomdownloadslinux-qemulinux-armpatchpatch -p1 -d linux lt linux-armpatchcd linuxmake ARCH=arm versatile_defconfigmake ARCH=arm menuconfig

Andrei CostinJonas Zaddach wwwfirmwarere 83104

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 84: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Compiling a Linux kernel for Qemu

Change the following kernel optionsGeneral Setup ---gt Cross-compiler tool prefix = (arm-linux-gnueabihf-)System Type ---gt [] Support ARM V6 processorSystem Type ---gt [] ARM errata Invalidation of the Instruction Cache operation can failFloating point emulation ---gt [] VFP-format floating point mathsKernel Features ---gt [] Use ARM EABI to compile the kernelKernel Features ---gt [] Allow old ABI binaries to run with this kernelBus Support ---gt [] PCI SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Device SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI Disk SupportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI CDROM supportDevice Drivers ---gt SCSI Device Support ---gt [] SCSI low-lever drivers ---gt

[] SYM53C8XX Version 2 SCSI supportDevice Drivers ---gt Generic Driver Options---gt

[] Maintain a devtmpfs filesystem to mount at devDevice Drivers ---gt Generic Driver Options---gt

[] Automount devtmpfs at dev after the kernel mounted the rootFile systems ---gt Pseudo filesystems---gt

[] Virtual memory file system support (former shm fs)Device Drivers ---gt Input device support---gt [] Event interfaceGeneral Setup ---gt [] Kernel config supportGeneral Setup ---gt [] Enable access to config through procconfiggzDevice Drivers ---gt Graphics Support ---gt Console display driver support ---gt

[ ] Select compiled-in fontsFile systems ---gt Select all file systems

Andrei CostinJonas Zaddach wwwfirmwarere 84104

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 85: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Compiling a Linux kernel for Qemu

make ARCH=arm -j8cp archarmbootzImage

or just download the kernel that we prepared for you here

Andrei CostinJonas Zaddach wwwfirmwarere 85104

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 86: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Get or compile Qemu

wget httpwikiqemu-projectorgdownloadqemu-151tarbz2tar xf qemu-151tarbz2cd qemu-151configure --target-list=arm-softmmumake -j8

or install the package of your distribution if it is recent(qemu-kvm-extras in Ubuntu 1204)

Andrei CostinJonas Zaddach wwwfirmwarere 86104

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 87: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Samsung Network HD Box Camerafirmware exercise

Andrei CostinJonas Zaddach wwwfirmwarere 87104

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 88: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Samsung Network HD Box Camerafirmware

bull Get the firmware from Samsungbull Unpack the firmware with BATtoolsfirmwarere_unpackshsnb7000_Series_200_121004zip mnttmp

Andrei CostinJonas Zaddach wwwfirmwarere 88104

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 89: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Samsung Network HD Box Camerafirmware

bull Inconveniently the kernel cannot mount the JFFS2 imagedirectly since it expects a mtd device

bull An easy solution to circumvent this problem is to convertthe JFFS2 image to an ext2 image

Andrei CostinJonas Zaddach wwwfirmwarere 89104

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 90: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Samsung Network HD Box Camerafirmware

dd if=devzero bs=1M count=300 of=mnttmpsnb7000_ext2img

sudo losetup devloop1 mnttmpsnb7000_ext2imgsudo mkfsext2 devloop1

(Note If you do this on your own machine double-check thatyou use the same loop device in both cases If you use HDDencryption then you might erase your drive by using the wrongcommand)sudo mkdir -p mnt2snbsudo mount devloop1 mnt2snbcp -fr datasnb7000_Series_200_121004zip-zip-1

snb7000_Series_200_121004img-gzip-1 tmp1hLfhz-tar-1work_snb7000dm365-jffs2-1 mnt2snb

sudo umount mnt2snbsudo losetup -d devloop1

Andrei CostinJonas Zaddach wwwfirmwarere 90104

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 91: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Start Qemu with Samsung NetworkHD Box Camera firmware

qemu-system-arm -M versatilepb -cpu arm1176 -m 256 -serial tcp1235servernowait -kernel zImage_3102 -hda ramdisk_snb7000dm365 -hdb snbext2 -net nic -net user -redir tcp80001022 -redir tcp800180 -redir tcp8002443 -redir tcp8003554-append root=devsda

console=ttyAMA0115200 console=tty init=binsh ip=1002152552552550snbeth0off

Andrei CostinJonas Zaddach wwwfirmwarere 91104

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 92: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Running the Samsung Network HDBox Camera firmware

bull Qemu starts up the system which greets you withsh-41

bull The shell inside is a little fragile ie Ctrl+C does not workto interrupt a command

bull So the first goal is to get the SSH server runningbull The second goal will be to get the Web Server running and

access some web applications

Andrei CostinJonas Zaddach wwwfirmwarere 92104

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 93: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Summary and Take-aways I

bull We took a firmware of an embedded device of interestbull For various reasons we might not have or not want to have

a device at handbull We heavily used automation to unpack itbull We have briefly analyzed it for important components files

and keywordsbull We have compiled a stock ARM kernel for embedded

device emulationbull We have compiled QEMU for ARM devices emulationbull We have automated (scriptable steps) firmware loading

into emulatorbull We have successfully logged into the shell of the emulated

device over SSH

Andrei CostinJonas Zaddach wwwfirmwarere 93104

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 94: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Summary and Take-aways II

bull We have successfully logged into the web-interface of theemulated device over HTTP and HTTPS

bull We have successfully extracted PEM private key used forSSL ndash it was protected by an EMPTY passphrase

bull We have successfully decrypted the SSL traffic includingrdquosecure over SSLrdquo web-login of the admin

bull We have successfully found the username and passwordby analyzing strings of the firmware and runningstrings-based HTTP basic-auth bruteforce script

Andrei CostinJonas Zaddach wwwfirmwarere 94104

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 95: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Summary and Take-aways III

bull Embedded devices and firmware security is an awesome topic)

bull Nevertheless security is totally missing (bull Reversing firmwares used to be hardbull Now it is much cheaper easier fasterbull Virtually any component of a firmware is vulnerablebull This includes web-interface crypto PKIIPSEC

unpatchedoutdated dependencieskernelsbull Backdooring is still there and is a real problem

Andrei CostinJonas Zaddach wwwfirmwarere 95104

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 96: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

Questions

Visit share and support our projectbull FIRMWAREREbull Upload upload upload We eat firmwares for breakfast

lunch and five orsquoclock teaContact us at (for trainings or general queries)

bull contactfirmwarerebull jonasfirmwarerebull andreifirmwarere

Andrei CostinJonas Zaddach wwwfirmwarere 96104

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 97: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

K THX C U BY

K THX C U BY

Andrei CostinJonas Zaddach wwwfirmwarere 97104

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 98: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

References IRooting sim cardshttpssrlabsderooting-sim-cards

Ciscorsquos backdoor for hackers March 2010httpwwwforbescom20100203hackers-networking-equipment-technology-security-ciscohtml

Brute forcing wi-fi protected setup November 2011httpsviehbfileswordpresscom201112viehboeck_wpspdf

Getting root on the human body August 2011httpwwwdarkreadingcomvulnerabilitygetting-root-on-the-human-body231300312

How digital detectives deciphered stuxnet the mostmenacing malware in history July 2011httparstechnicacomtech-policy201107how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history

Andrei CostinJonas Zaddach wwwfirmwarere 98104

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 99: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

References IIMedical device security under fire at black hat defconAugust 2011httpwwwdarkreadingcomevil-bytesmedical-device-security-under-fire-at-bl231500306

The hacker news More than 100000 wireless routers havedefault backdoor April 2012httpthehackernewscom201204more-than-100000-wireless-routers-havehtmlAttacks on scada systems are increasing July 2013httpwwwh-onlinecomsecuritynewsitemAttacks-on-SCADA-systems-are-increasing-1910302html

Cnet Top wi-fi routers easy to hack says study April 2013httpnewscnetcom8301-1009_3-57579981-83top-wi-fi-routers-easy-to-hack-says-study

Andrei CostinJonas Zaddach wwwfirmwarere 99104

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 100: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

References IIIExploiting soho routers April 2013httpsecurityevaluatorscomcontentcase-studiesrouterssoho_router_hacksjsp

[full-disclosure] sec consult sa-20130124-0 Critical sshbackdoor in multiple barracuda networks products January2013httparchivesneohapsiscomarchivesfulldisclosure2013-010221htmlIcs-cert monitor June 2013httpics-certus-certgovsitesdefaultfilesICS-CERT_Monitor_April-June2013_3pdf

The lessons of shamoon and stuxnet ignored Us ics stillvulnerable in the same way January 2013httpwwwinfosecurity-magazinecomview30058the-lessons-of-shamoon-and-stuxnet-ignored-us-ics-still-vulnerable-in-the-same-way

Andrei CostinJonas Zaddach wwwfirmwarere 100104

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 101: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

References IV

Millions of sim cards are rsquovulnerable to hack attackrsquo July2013httpwwwbbccouknewstechnology-23402988

Report Backdoor found in tp-link routers March 2013httphabrahabrrupost172799

Slashdot Backdoor found in tp-link routers March 2013httptechslashdotorgstory1303151234217backdoor-found-in-tp-link-routers

Tom CrossExploiting lawful intercept to wiretap the internet March2010httpwwwblackhatcompresentationsbh-dc-10Cross_TomBlackHat-DC-2010-Cross-Attacking-LawfulI-Intercept-wppdf

Andrei CostinJonas Zaddach wwwfirmwarere 101104

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 102: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

References V

Nicolas Falliere Liam O Murchu and Eric ChienW32stuxnet dossier February 2011httpwwwsymanteccomcontentenusenterprisemediasecurity_responsewhitepapersw32_stuxnet_dossierpdf

D Halperin TS Heydt-Benjamin B Ransford SS ClarkB Defend W Morgan K Fu T Kohno and WH MaiselPacemakers and implantable cardiac defibrillatorsSoftware radio attacks and zero-power defensesIn Security and Privacy 2008 SP 2008 IEEE Symposiumon pages 129ndash142 2008httpwwwsecure-medicineorgpublicpublicationsicd-studypdf

Andrei CostinJonas Zaddach wwwfirmwarere 102104

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 103: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

References VI

Collin Mulliner and Benjamin MicheacuteleRead it twice a mass-storage-based tocttou attackIn Proceedings of the 6th USENIX conference on OffensiveTechnologies pages 11ndash11 USENIX Association 2012

Jerome RadcliffeHacking medical devices for fun and insulin Breaking thehuman scada system August 2011httpcsunoedu~dbilarBH-US-2011materialsRadcliffeBH_US_11_Radcliffe_Hacking_Medical_Devices_WPpdf

Roman UnucheckThe most sophisticated android trojan June 2013httpwwwsecurelistcomenblog8106The_most_sophisticated_Android_Trojan

Andrei CostinJonas Zaddach wwwfirmwarere 103104

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104

Page 104: Embedded Devices Security Firmware Reverse Engineeringandreicostin.com/papers/bh13us_firmware.re_slides.pdf · (IEEE) • IEEE Standard Glossary of Software ... hardware device or

References VII

Ryan WhitwamKaspersky researchers discover most advanced androidmalware yet June 2013httpwwwandroidpolicecom20130607kaspersky-researchers-discover-most-advanced-android-malware-yet

Andrei CostinJonas Zaddach wwwfirmwarere 104104