SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
Dynamically Overriding Mac OS X
                           Down the Rabbit Hole
                              Jonathan ‘Wolf’ Rentzsch
                                 http://rentzsch.com




Monday, February 9, 2009
“These rules are no different than
  those of a computer system.

                 Some of them can be bent.
                  Others... can be broken.”
                                   —Morpheus
Monday, February 9, 2009
What Happened to
                How to Hack Mac OS X?
           The paper’s original title was “How to Hack Mac OS X”
           However, “hacking” is just too abused, especially in the
           Unix realm.
           Really, think “trap patching”. However:
                 On Mac OS X, traps aren’t used nearly as often.
                 “Patching” also has a specific definition in the Unix
                 realm: applying textual differences to source code.
           Thus, “dynamic overriding”.
Monday, February 9, 2009
Dynamic Overriding Defined
           The ability to modify software at runtime...
                 ...often in ways not originally anticipated by the
                 software’s original authors.
           Can suppress, change or extend existing functionality.
           Can add wholly new functionality to existing software.
           The modifications exist only in memory:
                 Never written to disk (save VM swapping).
                 Not permanent.
                 Easy to rollback — restart the app.
Monday, February 9, 2009
Dynamic Overriding
                                    Overriding:
                           Made possible by two
                           techniques that work
                                 together

            Function    Code
           Overriding Injection
Monday, February 9, 2009
Function Overriding
           Unlike the classic Mac OS, Mac OS X does not
           directly support dynamically overriding system
           functions.
           At best, APIs exposed with Objective C interfaces can
           be overridden with categories and/or posing. Major
           limitations:
                 Requires the API be exposed in ObjC. Excludes all of
                 Mach, BSD and Carbon.
                 Overriding an ObjC wrapper does not override the
                 original function. Override will not effect all of the
                 app if it has mixed procedural/objective code.
Monday, February 9, 2009
Function Overriding
           Ideally, overriding a system function would be simple:
                 Discover the function’s entry in a universal table.
                 Save off a pointer to the original code.
                 Replace it with a pointer to your overriding code.
           Alas, Mach’s linking model lacks any sort of centralized
           bottleneck. This stands in contrast to CFM.




Monday, February 9, 2009
CFM’s Model
                              Exporter-Owned Vector Table (i.e. CFM)
                              App Module
                                                    System Module
                           implementation block
                                                   implementation block

                               loadPlugins
                                                            free

                                   main
                                                           calloc


                           vector table (import)           malloc
                                   main
                               loadPlugins
                                                    vector table (export)
                                  malloc
                                                           malloc
                                                           calloc
                            Plugin Module
                                                            free
                           implementation block


                                   main



                           vector table (import)

                                   main
                                  malloc




Monday, February 9, 2009
CFM vs Mach
            Exporter-Owned Vector Table (i.e. CFM)            Importer-Owned Vector Table (i.e. Mach)
            App Module                                       App Module
                                  System Module
         implementation block                             implementation block
                                 implementation block

              loadPlugins                                     loadPlugins
                                          free
                                                                                   System Module
                  main                                            main
                                                                                  implementation block
                                         calloc

                                                                                           free
         vector table (import)                            vector table (import)
                                         malloc
                  main                                            main
                                                                                          calloc
              loadPlugins                                     loadPlugins
                                  vector table (export)
                 malloc                                          malloc
                                         malloc                                           malloc
                                         calloc
           Plugin Module                                   Plugin Module
                                          free
         implementation block                             implementation block     vector table (export)

                                                                                          malloc
                                                                  main
                  main
                                                                                          calloc
                                                                                           free
                                                          vector table (import)
         vector table (import)

                                                                  main
                  main
                                                                 malloc
                 malloc



Monday, February 9, 2009
Function Overriding
           You may think that you could walk all loaded modules
           to discover and rewrite all their vector tables.
           That won’t work:
                 Lazy binding means symbols aren’t resolved until
                 they’re first used.You’d have to force resolving of all
                 symbols before rewriting: expensive and tricky.
                 All the work needs to be done again when a new
                 module is loaded.
                 Won’t work for symbols looked up programatically.

Monday, February 9, 2009
Function Overriding
           What will work: rewrite the original function
           implementation, in memory, itself.
           Basic premise: replace the original function’s first
           instruction with a branch instruction to the desired
           override code.
           This technique is known as single-instruction
           overwriting.
           You may shudder now...



Monday, February 9, 2009
Single-Instruction Overwriting
           Benefits:
                 Atomic replacement. Safe in the face of multiple
                 preemptive threads calling the original function.
                 Less likely to harmfully impact the original code. If you
                 wish to reenter the original function from the
                 override, you’ll need to re-execute the replaced
                 instruction. Moving less code around makes this
                 more likely to work.
                 Compatibility. Works with the widest variety of
                 function prologs and other patching
                 implementations (including our own!)
Monday, February 9, 2009
Single-Instruction Overwriting
           Replacing a single instruction is good, but limiting.
           Can’t branch to an arbitrary address, as that would
           take at least three instructions.
           Leaves us with branch instructions that encode their
           targets:
                 b (branch relative)
                 ba (branch absolute)
                 bl (branch relative, update link register)
                 bla (branch absolute, update link regiter)
Monday, February 9, 2009
Single-Instruction Overwriting
           bl and bla go away since they stomp on the link
           register — that houses the caller’s return address!
           b and ba embed a 4-byte-aligned, 24-bit address.
           For b, that’s ±32MB relative to the current program
           counter. We really can’t guarantee our override will
           be within 32MB of the original function.
           For ba, that’s the lowermost and uppermost 32MB of
           the current address space. The lowermost 32MB
           tends to be busy with loaded code and data.
           That leaves ba’s uppermost 32MB of address space.
Monday, February 9, 2009
The Branch Island
           We can allocate a single page at the end of the
           address space to hold our branch island.
           (Mach’s sparse memory model works nicely here.)
           The branch island acts as a level of indirection,
           allowing the address-limited ba to effectively target
           any address.
           Two uses for branch islands: escape and reentry.




Monday, February 9, 2009
Branch Islands
           Escape branch island (required):
                 Used to jump from the original function to the
                 overriding function.
                 Allocated at the end of the address space.
                 What our generated ba instruction points at.
           Reentry branch island:
                 Optional, only generated if you wish to reenter the
                 original function.
                 Houses the original function’s first instruction.
Monday, February 9, 2009
Inside the Branch Island
           C definition:
           long kIslandTemplate[] = {
              0x9001FFFC,
              0x3C00DEAD,
              0x6000BEEF,
              0x7C0903A6,
              0x8001FFFC,
              0x60000000,
              0x4E800420
           };
           What, you guys don’t read machine language?!?

Monday, February 9, 2009
Branch Islands for Dummies
                  Opcode          Assembly            Comment
                                            save off original r0 into
   0x9001FFFC              stw r0,-4(SP)
                                            red zone
                                            load the high half of
   0x3C00DEAD              lis r0,0xDEAD
                                            address
                                            load the low half of
   0x6000BEEF              ori r0,r0,0xBEEF
                                            address
                                            load target into counter
   0x7C0903A6              mtctr r0
                                            register
                                                restore original r0
   0x8001FFFC              lwz r0,-4(SP)
                                                optional original first
   0x60000000              nop
                                                instruction (for
                                                reentry) the target in
                                                branch to
   0x4E800420              bctr
                                                counter register
Monday, February 9, 2009
Lame Override Animation
                           ! Initial State




                                        myMalloc




                                         malloc


                                       malloc client




Monday, February 9, 2009
Lame Override Animation
                           ! Escape Island Allocated
                             and Targeted



                                       myMalloc


                                     escape island


                                        malloc


                                     malloc client




Monday, February 9, 2009
Lame Override Animation
                           ! Reentry Island Allocated,
                             Targeted & Engaged

                                     reentry island


                                       myMalloc


                                     escape island


                                        malloc


                                      malloc client




Monday, February 9, 2009
Lame Override Animation
                           ! Escape Island Atomically
                             Engaged
                                     reentry island


                                       myMalloc


                                     escape island


                                        malloc


                                     malloc client




Monday, February 9, 2009
Function Overriding Details
           Discover the function’s address. Use
           _dyld_lookup_and_bind[with_hint]()
           and NSIsSymbolNameDefined[WithHint]().
           Test the waters. Watch out for functions that start with
           the mfctr instruction.
           Make the original function writable. vm_protect().
           Allocate the escape island. Use vm_allocate().
           Target the escape island and make it executable. Use
           msync().

Monday, February 9, 2009
Function Overriding Details
           Build the branch instruction. Target the escape island.
           Optionally allocate and engage the reentry island.
           Atomically:
                 Insert the original function’s first instruction into the
                 reentry island. If reentry is desired.
                 Target the reentry island and make it executable. Again,
                 if reentry is desired.
                 Swap the original function’s first instruction with the
                 generated ba instruction. If atomic replacement fails
                 (unlikely), loop and try again.
Monday, February 9, 2009
Code Injection Overview
           Function overriding is a powerful technique, but it’s
           only attains half of our goal.
           By itself, we can only override system functions in our
           own software.
           Code injection, on the other hand, allows us override
           application and system functions in any process.
           Not just override functions, but inject new Objective
           C classes (example: for posing)



Monday, February 9, 2009
Code Injection Overview
           Mach supplies everything we need.
           It’s just not very well documented. ; )
           Specifically, Mach provides APIs for:
                 Remote memory allocation. (vm_allocate())
                 Remote memory I/O. (vm_write())
                 Remote thread allocation. (thread_create())
                 Remote thread control.
                 (thread_create_running())

Monday, February 9, 2009
Code Injection Details
           Allocate a remote thread stack. No need to populate it
           — parameters will be passed in registers.
           Allocate and populate the thread’s code block. The gotcha
           here is determining the thread entry’s code size. It’s
           surprisingly hard, and requires a calling the dynamic
           loader APIs and stat()’ing the file system!
           Allocate, populate and start the thread. Set the thread
           control block’s srr0 to the code block, r1 to the
           stack, r3 through r10 to parameters and lr to
           0xDEADBEEF (this thread should never return).

Monday, February 9, 2009
Code Injection Leakage
           While the injected thread can stop itself, it can’t
           delete itself (it would need to deallocate its own stack
           and code while running).
           May be work-arounds, like the injected thread
           spawning another “normal” cleanup thread.
           Another solution is to install a permanent “injection
           manager” thread, that would start a Mach server to
           handle future injections via IPC.
                 Bonus feature: such an “injection server” would
                 eliminate the need to start a new thread per
                 injection.
Monday, February 9, 2009
Code & Doc Availability
           Two packages, both written in C:
                 mach_override: Implements function overriding.
                       http://rentzsch.com/mach_override
                 mach_inject: Implements code injection.
                       http://rentzsch.com/mach_inject
                 Code is hosted by Extendamac (BSD-style license)
                       http://extendamac.sourceforge.net


Monday, February 9, 2009
Conclusion


                            “Whoa.”
                                   —Neo




Monday, February 9, 2009

Weitere ähnliche Inhalte

Ähnlich wie Dynamic Overriding

Pragmatic Model Driven Development using openArchitectureWare
Pragmatic Model Driven Development using openArchitectureWarePragmatic Model Driven Development using openArchitectureWare
Pragmatic Model Driven Development using openArchitectureWareMichael Vorburger
 
JVL MacComm OCX File
JVL MacComm OCX FileJVL MacComm OCX File
JVL MacComm OCX FileElectromate
 
Plugin-based IVI Architectures with Qt
Plugin-based IVI Architectures with Qt Plugin-based IVI Architectures with Qt
Plugin-based IVI Architectures with Qt ICS
 
Build Comet applications using Scala, Lift, and <b>jQuery</b>
Build Comet applications using Scala, Lift, and <b>jQuery</b>Build Comet applications using Scala, Lift, and <b>jQuery</b>
Build Comet applications using Scala, Lift, and <b>jQuery</b>tutorialsruby
 
<img src="../i/r_14.png" />
<img src="../i/r_14.png" /><img src="../i/r_14.png" />
<img src="../i/r_14.png" />tutorialsruby
 
Linux KVM のコードを追いかけてみよう
Linux KVM のコードを追いかけてみようLinux KVM のコードを追いかけてみよう
Linux KVM のコードを追いかけてみようTsuyoshi OZAWA
 
A simplest way to reconstruct .Net Framework - CRB Tech
A simplest way to reconstruct .Net Framework - CRB TechA simplest way to reconstruct .Net Framework - CRB Tech
A simplest way to reconstruct .Net Framework - CRB TechPooja Gaikwad
 
A simplest-way-to-reconstruct-.net-framework
A simplest-way-to-reconstruct-.net-frameworkA simplest-way-to-reconstruct-.net-framework
A simplest-way-to-reconstruct-.net-frameworksonia merchant
 
On Software Release Engineering (Bram Adams)
On Software Release Engineering (Bram Adams)On Software Release Engineering (Bram Adams)
On Software Release Engineering (Bram Adams)Bram Adams
 
Makefile
MakefileMakefile
MakefileIonela
 
Flex Continuous Quality Builds Flex & (Ant || Maven)
Flex Continuous Quality Builds Flex & (Ant || Maven)Flex Continuous Quality Builds Flex & (Ant || Maven)
Flex Continuous Quality Builds Flex & (Ant || Maven)François Le Droff
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectureselliando dias
 
Building the VM
Building the VMBuilding the VM
Building the VMESUG
 
Caliburn.micro
Caliburn.microCaliburn.micro
Caliburn.microbwullems
 
IBM’s System Director VMControl: Advanced Multi-Platform Virtualization Manag...
IBM’s System Director VMControl: Advanced Multi-Platform Virtualization Manag...IBM’s System Director VMControl: Advanced Multi-Platform Virtualization Manag...
IBM’s System Director VMControl: Advanced Multi-Platform Virtualization Manag...IBM India Smarter Computing
 
COMPARATIVE STUDY OF MATLAB AND ITS OPEN SOURCE ALTERNATIVE SCILAB
COMPARATIVE STUDY OF MATLAB AND ITS OPEN SOURCE ALTERNATIVE SCILABCOMPARATIVE STUDY OF MATLAB AND ITS OPEN SOURCE ALTERNATIVE SCILAB
COMPARATIVE STUDY OF MATLAB AND ITS OPEN SOURCE ALTERNATIVE SCILABWildan Maulana
 

Ähnlich wie Dynamic Overriding (20)

Pragmatic Model Driven Development using openArchitectureWare
Pragmatic Model Driven Development using openArchitectureWarePragmatic Model Driven Development using openArchitectureWare
Pragmatic Model Driven Development using openArchitectureWare
 
JVL MacComm OCX File
JVL MacComm OCX FileJVL MacComm OCX File
JVL MacComm OCX File
 
Plugin-based IVI Architectures with Qt
Plugin-based IVI Architectures with Qt Plugin-based IVI Architectures with Qt
Plugin-based IVI Architectures with Qt
 
Build Comet applications using Scala, Lift, and <b>jQuery</b>
Build Comet applications using Scala, Lift, and <b>jQuery</b>Build Comet applications using Scala, Lift, and <b>jQuery</b>
Build Comet applications using Scala, Lift, and <b>jQuery</b>
 
<img src="../i/r_14.png" />
<img src="../i/r_14.png" /><img src="../i/r_14.png" />
<img src="../i/r_14.png" />
 
Nuxeo 5.2 Glassfish
Nuxeo 5.2 GlassfishNuxeo 5.2 Glassfish
Nuxeo 5.2 Glassfish
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Linux KVM のコードを追いかけてみよう
Linux KVM のコードを追いかけてみようLinux KVM のコードを追いかけてみよう
Linux KVM のコードを追いかけてみよう
 
Acceleo Code Generation
Acceleo Code GenerationAcceleo Code Generation
Acceleo Code Generation
 
A simplest way to reconstruct .Net Framework - CRB Tech
A simplest way to reconstruct .Net Framework - CRB TechA simplest way to reconstruct .Net Framework - CRB Tech
A simplest way to reconstruct .Net Framework - CRB Tech
 
A simplest-way-to-reconstruct-.net-framework
A simplest-way-to-reconstruct-.net-frameworkA simplest-way-to-reconstruct-.net-framework
A simplest-way-to-reconstruct-.net-framework
 
On Software Release Engineering (Bram Adams)
On Software Release Engineering (Bram Adams)On Software Release Engineering (Bram Adams)
On Software Release Engineering (Bram Adams)
 
Makefile
MakefileMakefile
Makefile
 
Flex Continuous Quality Builds Flex & (Ant || Maven)
Flex Continuous Quality Builds Flex & (Ant || Maven)Flex Continuous Quality Builds Flex & (Ant || Maven)
Flex Continuous Quality Builds Flex & (Ant || Maven)
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectures
 
Mac OS X Manual
Mac OS X ManualMac OS X Manual
Mac OS X Manual
 
Building the VM
Building the VMBuilding the VM
Building the VM
 
Caliburn.micro
Caliburn.microCaliburn.micro
Caliburn.micro
 
IBM’s System Director VMControl: Advanced Multi-Platform Virtualization Manag...
IBM’s System Director VMControl: Advanced Multi-Platform Virtualization Manag...IBM’s System Director VMControl: Advanced Multi-Platform Virtualization Manag...
IBM’s System Director VMControl: Advanced Multi-Platform Virtualization Manag...
 
COMPARATIVE STUDY OF MATLAB AND ITS OPEN SOURCE ALTERNATIVE SCILAB
COMPARATIVE STUDY OF MATLAB AND ITS OPEN SOURCE ALTERNATIVE SCILABCOMPARATIVE STUDY OF MATLAB AND ITS OPEN SOURCE ALTERNATIVE SCILAB
COMPARATIVE STUDY OF MATLAB AND ITS OPEN SOURCE ALTERNATIVE SCILAB
 

Kürzlich hochgeladen

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Kürzlich hochgeladen (20)

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Dynamic Overriding

  • 1. Dynamically Overriding Mac OS X Down the Rabbit Hole Jonathan ‘Wolf’ Rentzsch http://rentzsch.com Monday, February 9, 2009
  • 2. “These rules are no different than those of a computer system. Some of them can be bent. Others... can be broken.” —Morpheus Monday, February 9, 2009
  • 3. What Happened to How to Hack Mac OS X? The paper’s original title was “How to Hack Mac OS X” However, “hacking” is just too abused, especially in the Unix realm. Really, think “trap patching”. However: On Mac OS X, traps aren’t used nearly as often. “Patching” also has a specific definition in the Unix realm: applying textual differences to source code. Thus, “dynamic overriding”. Monday, February 9, 2009
  • 4. Dynamic Overriding Defined The ability to modify software at runtime... ...often in ways not originally anticipated by the software’s original authors. Can suppress, change or extend existing functionality. Can add wholly new functionality to existing software. The modifications exist only in memory: Never written to disk (save VM swapping). Not permanent. Easy to rollback — restart the app. Monday, February 9, 2009
  • 5. Dynamic Overriding Overriding: Made possible by two techniques that work together Function Code Overriding Injection Monday, February 9, 2009
  • 6. Function Overriding Unlike the classic Mac OS, Mac OS X does not directly support dynamically overriding system functions. At best, APIs exposed with Objective C interfaces can be overridden with categories and/or posing. Major limitations: Requires the API be exposed in ObjC. Excludes all of Mach, BSD and Carbon. Overriding an ObjC wrapper does not override the original function. Override will not effect all of the app if it has mixed procedural/objective code. Monday, February 9, 2009
  • 7. Function Overriding Ideally, overriding a system function would be simple: Discover the function’s entry in a universal table. Save off a pointer to the original code. Replace it with a pointer to your overriding code. Alas, Mach’s linking model lacks any sort of centralized bottleneck. This stands in contrast to CFM. Monday, February 9, 2009
  • 8. CFM’s Model Exporter-Owned Vector Table (i.e. CFM) App Module System Module implementation block implementation block loadPlugins free main calloc vector table (import) malloc main loadPlugins vector table (export) malloc malloc calloc Plugin Module free implementation block main vector table (import) main malloc Monday, February 9, 2009
  • 9. CFM vs Mach Exporter-Owned Vector Table (i.e. CFM) Importer-Owned Vector Table (i.e. Mach) App Module App Module System Module implementation block implementation block implementation block loadPlugins loadPlugins free System Module main main implementation block calloc free vector table (import) vector table (import) malloc main main calloc loadPlugins loadPlugins vector table (export) malloc malloc malloc malloc calloc Plugin Module Plugin Module free implementation block implementation block vector table (export) malloc main main calloc free vector table (import) vector table (import) main main malloc malloc Monday, February 9, 2009
  • 10. Function Overriding You may think that you could walk all loaded modules to discover and rewrite all their vector tables. That won’t work: Lazy binding means symbols aren’t resolved until they’re first used.You’d have to force resolving of all symbols before rewriting: expensive and tricky. All the work needs to be done again when a new module is loaded. Won’t work for symbols looked up programatically. Monday, February 9, 2009
  • 11. Function Overriding What will work: rewrite the original function implementation, in memory, itself. Basic premise: replace the original function’s first instruction with a branch instruction to the desired override code. This technique is known as single-instruction overwriting. You may shudder now... Monday, February 9, 2009
  • 12. Single-Instruction Overwriting Benefits: Atomic replacement. Safe in the face of multiple preemptive threads calling the original function. Less likely to harmfully impact the original code. If you wish to reenter the original function from the override, you’ll need to re-execute the replaced instruction. Moving less code around makes this more likely to work. Compatibility. Works with the widest variety of function prologs and other patching implementations (including our own!) Monday, February 9, 2009
  • 13. Single-Instruction Overwriting Replacing a single instruction is good, but limiting. Can’t branch to an arbitrary address, as that would take at least three instructions. Leaves us with branch instructions that encode their targets: b (branch relative) ba (branch absolute) bl (branch relative, update link register) bla (branch absolute, update link regiter) Monday, February 9, 2009
  • 14. Single-Instruction Overwriting bl and bla go away since they stomp on the link register — that houses the caller’s return address! b and ba embed a 4-byte-aligned, 24-bit address. For b, that’s ±32MB relative to the current program counter. We really can’t guarantee our override will be within 32MB of the original function. For ba, that’s the lowermost and uppermost 32MB of the current address space. The lowermost 32MB tends to be busy with loaded code and data. That leaves ba’s uppermost 32MB of address space. Monday, February 9, 2009
  • 15. The Branch Island We can allocate a single page at the end of the address space to hold our branch island. (Mach’s sparse memory model works nicely here.) The branch island acts as a level of indirection, allowing the address-limited ba to effectively target any address. Two uses for branch islands: escape and reentry. Monday, February 9, 2009
  • 16. Branch Islands Escape branch island (required): Used to jump from the original function to the overriding function. Allocated at the end of the address space. What our generated ba instruction points at. Reentry branch island: Optional, only generated if you wish to reenter the original function. Houses the original function’s first instruction. Monday, February 9, 2009
  • 17. Inside the Branch Island C definition: long kIslandTemplate[] = { 0x9001FFFC, 0x3C00DEAD, 0x6000BEEF, 0x7C0903A6, 0x8001FFFC, 0x60000000, 0x4E800420 }; What, you guys don’t read machine language?!? Monday, February 9, 2009
  • 18. Branch Islands for Dummies Opcode Assembly Comment save off original r0 into 0x9001FFFC stw r0,-4(SP) red zone load the high half of 0x3C00DEAD lis r0,0xDEAD address load the low half of 0x6000BEEF ori r0,r0,0xBEEF address load target into counter 0x7C0903A6 mtctr r0 register restore original r0 0x8001FFFC lwz r0,-4(SP) optional original first 0x60000000 nop instruction (for reentry) the target in branch to 0x4E800420 bctr counter register Monday, February 9, 2009
  • 19. Lame Override Animation ! Initial State myMalloc malloc malloc client Monday, February 9, 2009
  • 20. Lame Override Animation ! Escape Island Allocated and Targeted myMalloc escape island malloc malloc client Monday, February 9, 2009
  • 21. Lame Override Animation ! Reentry Island Allocated, Targeted & Engaged reentry island myMalloc escape island malloc malloc client Monday, February 9, 2009
  • 22. Lame Override Animation ! Escape Island Atomically Engaged reentry island myMalloc escape island malloc malloc client Monday, February 9, 2009
  • 23. Function Overriding Details Discover the function’s address. Use _dyld_lookup_and_bind[with_hint]() and NSIsSymbolNameDefined[WithHint](). Test the waters. Watch out for functions that start with the mfctr instruction. Make the original function writable. vm_protect(). Allocate the escape island. Use vm_allocate(). Target the escape island and make it executable. Use msync(). Monday, February 9, 2009
  • 24. Function Overriding Details Build the branch instruction. Target the escape island. Optionally allocate and engage the reentry island. Atomically: Insert the original function’s first instruction into the reentry island. If reentry is desired. Target the reentry island and make it executable. Again, if reentry is desired. Swap the original function’s first instruction with the generated ba instruction. If atomic replacement fails (unlikely), loop and try again. Monday, February 9, 2009
  • 25. Code Injection Overview Function overriding is a powerful technique, but it’s only attains half of our goal. By itself, we can only override system functions in our own software. Code injection, on the other hand, allows us override application and system functions in any process. Not just override functions, but inject new Objective C classes (example: for posing) Monday, February 9, 2009
  • 26. Code Injection Overview Mach supplies everything we need. It’s just not very well documented. ; ) Specifically, Mach provides APIs for: Remote memory allocation. (vm_allocate()) Remote memory I/O. (vm_write()) Remote thread allocation. (thread_create()) Remote thread control. (thread_create_running()) Monday, February 9, 2009
  • 27. Code Injection Details Allocate a remote thread stack. No need to populate it — parameters will be passed in registers. Allocate and populate the thread’s code block. The gotcha here is determining the thread entry’s code size. It’s surprisingly hard, and requires a calling the dynamic loader APIs and stat()’ing the file system! Allocate, populate and start the thread. Set the thread control block’s srr0 to the code block, r1 to the stack, r3 through r10 to parameters and lr to 0xDEADBEEF (this thread should never return). Monday, February 9, 2009
  • 28. Code Injection Leakage While the injected thread can stop itself, it can’t delete itself (it would need to deallocate its own stack and code while running). May be work-arounds, like the injected thread spawning another “normal” cleanup thread. Another solution is to install a permanent “injection manager” thread, that would start a Mach server to handle future injections via IPC. Bonus feature: such an “injection server” would eliminate the need to start a new thread per injection. Monday, February 9, 2009
  • 29. Code & Doc Availability Two packages, both written in C: mach_override: Implements function overriding. http://rentzsch.com/mach_override mach_inject: Implements code injection. http://rentzsch.com/mach_inject Code is hosted by Extendamac (BSD-style license) http://extendamac.sourceforge.net Monday, February 9, 2009
  • 30. Conclusion “Whoa.” —Neo Monday, February 9, 2009