SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Light and Dark side of Code
      Instrumentation
  Dmitriy “D1g1″ Evdokimov
  DSecRG, Security Researcher
#whoami
• Security Researcher in DSecRG
       – RE
       – Fuzzing
       – Mobile security
• Organizer: DCG #7812
• Editor in “XAKEP”



Digital Security           Positive Hack Days 2012   2
Agenda
1.      Instrumentation .
2.      Instrumentation ..
3.      Instrumentation …
4.      Instrumentation ….
5.      Instrumentation …..
6.      Instrumentation ……
7.      Instrumentation …….

Digital Security       Positive Hack Days 2012   3
Intro


“It has been proved by scientists that a new
   point of evolution, any technical progress
   appears when a Man makes up a new type of
   tool, but not a product.”



Digital Security   Positive Hack Days 2012      4
Instrumentation
Instrumentation is a technique adding extra
  code to an program/environment for
  monitoring/change some program behavior.

                                                Environment

          Program                                Program


                    Own                                       Own
                    extra                                     extra
                    code                                      code


Digital Security                Positive Hack Days 2012               5
Why is it necessary?
                                             Parallel optimization
                   Simulation
                                                                            Memory debugging
                                Virtualization
                                                          Emulation
                                                                                  Software profiling
   Performance analysis
                                                                  Testing
                            Automated debugging                                     Correctness checking
                        Error detection                            Collecting code metrics


          Binary translation                     Optimization
                                                                            Memory leak detection




Digital Security                                 Positive Hack Days 2012                               6
Instrumentation in information
                        security
                   Control flow analysis             Security test case generation

                                      Unpack                    Code coverage
          Virtual patching                 Malware analysis                  Vulnerability detection
                      Privacy monitoring                       Taint analysis
                                                                                   Antivirus technology
        Sandboxing                               Program shepherding
                           Data flow analysis                         Shellcode detection
  Deobfuscation                                                                             Fuzzing
                                                  Reverse engineering
                    Behavior based security                                     Forensic
                               Transparent debugging
                                                              Data Structure Restoring
        Security enforcement


Digital Security                            Positive Hack Days 2012                                    7
Analysis
                   Criterion    Static analysis          Dynamic analysis

              Code vs. data         Problem                No problem

            Code coverage      Big (but not all)             One way

    Information about values   No information             All information

        Self-modifying code         Problem                No problem

        Interaction with the            No                     Yes
            environment
              Unused code           Analysis               No analysis

                   JIT code         Problem                No problem



Digital Security               Positive Hack Days 2012                      8
Code Discovery

                                    Memory

After static analysis     0101010110101001010010
                                  Instr 1               After dynamic analysis
                          0101010101101010101010
                           Instr 2     Instr 3
                          1111010101110101000111
                           jump reg   InstrDATA
                                            4 Instr
                          1011100111001010101011
                           5 Instr 4 6
                                Instr     Instr 7
                                                5
                          jmp 0x0ABCD PADDING
                          0111010110100111100110
                           Instr 7 cont. Instr 8
                          1010101101110001001011
                          Instr 9 Instr 6 10
                                      Instr




 Digital Security             Positive Hack Days 2012                       9
The general scheme of code
                        instrumentation
1.      Find points of instrumentation;
2.      Insert instrumentation;
3.      Take control from program;
4.      Save context of the program;
5.      Execute own code;
6.      Restore context of the program;
7.      Return control to program.

Digital Security            Positive Hack Days 2012   10
Source Data
                             Source data




          Source code         Byte code             Binary code




Digital Security          Positive Hack Days 2012                 11
Classification of target
                       instrumentation
                                Instrumentation


 With source code                            Without source code


       Source code               Byte code                     Binary code

     Linker/Compiler                Byte code                      Executable file

                                  Interpreter/VM                      Process

       Environment
       Dynamic binary instrumentation
       Static binary modification
       Byte code instrumentation
       Link-time/Compilation-time
       Source code instrumentation                                 Environment
       - Static
       instrumentation
                                                                     Hardware
       - Load-time
Digital- Dynamic
        Security           Positive Hack Days 2012                                   12
Source code instrumentation
• Source code*
       – Source code instrumentation
               • Manual skills
               • Plugins for IDE
       – Link-time/Compilation-time instrumentation
               • Options of linker/compiler


• Tools: Visual Studio Profiler, gcc, TAU, OPARI,
  Diablo, Phoenix, LLVM, Rational Purify, Valgrind
        *Unreal condition for security specialist =)
Digital Security                       Positive Hack Days 2012   13
Unmoral programming




Digital Security         Positive Hack Days 2012   14
Byte code instrumentation
Byte code – intermediate representation
  between source code and machine code.



                                                                    …


        Java VM         Dalvik VM                AVM/AVM2     CLR




Digital Security                    Positive Hack Days 2012             15
Instrumentation byte-code (I)
                   Source code         Compilation                 Byte-code




                                                                        Load
                             Virtual machine



                                                                       Loader
                                                                                       JIT

                                 Lib




                                                                                       Execute
                                       Lib
                                             Lib



                                                                               Machine code

Digital Security                             Positive Hack Days 2012                             16
Instrumentation byte code (II)
• Byte-code
       – Static instrumentation
               • Static byte code instrumentation
       – Load-time instrumentation
               • Custom byte code loader
       – Dynamic instrumentation
               • Dynamic byte code instrumentation




Digital Security                 Positive Hack Days 2012   17
Instrumentation Java (I)

            Mechanisms:
                   • java.lang.instrument package;
                   • Java Platform Debugger Architecture (JPDA) .




Digital Security                 Positive Hack Days 2012            18
Instrumentation Java (II)
• Static instrumentation
       – Modification *.class files
• Load-time instrumentation
       – ClassFileLoadHook
       – Custom ClassLoader
• Dynamic instrumentation
       – ClassFileLoadHook -> RetransformClasses

Tools: Javassist, ObjectWeb ASM, BCEL, JOIE, reJ
  JavaSnoop, Serp, JMangler

Digital Security             Positive Hack Days 2012   19
Instrumentation .NET
• Static instrumentation
       – Modification DLL files
• Load-time instrumentation
       – AppDomain.Load()/Assembly.Load()
       – Joint redirection
       – Via event handler



Tools: ReFrameworker, MBEL, RAIL, Cecil
Digital Security          Positive Hack Days 2012   20
Instrumentation ActionScript (I)
• ActionScript2
       – AVM
       – Tags that (can) contain bytecode:
               • DefineButton (7), DefineButton2 (34), DefineSprite (39),
                 DoAction (12), DoInitAction (59), PlaceObject2 (26),
                 PlaceObject3 (70).
• ActionScript3
       – AVM2
       – Tags that (can) contain bytecode:
               • DoABC (82), RawABC (72).

Digital Security                  Positive Hack Days 2012              21
AVM2 Architecture
                             AS3
                          .abc
                   function (x:int):int {
                     return x+10
                   }
                      .abc parser
                                                                       MIR
                                                                  JIT Compiler
                             .abc
                                                              @1 arg +8// argv
                   getlocal 1 Verifier
                    Bytecode                                   MIR Code Generator
                                                              @2 load [@1+4]
                   pushint 10
                                                              @3 imm 10
                   add
                                                              @4 add (@2,@3)
                   returnvalue
                       Interpreter                             MD Code Generator
                                                              @5 ret @4 // @4:eax
                                                              (x86, PPC, ARM, etc.)

                                                            x86
                          Runtime System (Type System, Object Model)
                                                   mov eax,(eap+8)
                                                   mov eax,(eax+4)
                                                   add eax,10
                             Memory Manager/Garbage Collector
                                                   ret
Digital Security                            Positive Hack Days 2012                   22
Instrumentation ActionScript (I)
                       AVM tag
   Original SWF file




           Header                              Tags




Instrumenteted
SWF file



    Digital Security             Positive Hack Days 2012   23
Instrumentation AVM (II)
• Static instrumentation
       – Add :
               •   trace()
               •   dump()
               •   debug()
               •   debugfile()
               •   debugline()
       – Modification:
               • Create own class + change class name = hook!

Digital Security                 Positive Hack Days 2012        24
Instrumentation binary code
• The executable file                                   • Environment
       – Static code instrumentation                           – Modifying call table
               • Static binary instrumentation                     • IDT, CPU MSRs, GDT, SSDT,
• Process                                                            IRP тable
       – Debuggers                                                 • …
               • Debugging API                                 – Modifying OS options
       – Modifying call table/other structure                      •   SHIM
               • IAT                                               •   LD_PRELOAD
               • …                                                 •   AppInt_DLLs
       – Dynamic code instrumentation                              •   DLL injection
               • Dynamic binary instrumentation                    •   …
• Hardware                                                     – Reproduction of the
       – Hardware debug features                                 environment
               • Debug registers                                   • Emulation
               • Hardware debuggers                                • Virtualization
               • …

Digital Security                         Positive Hack Days 2012                             25
Static Binary Instrumentation (I)
Static binary instrumentation/Physical code
  integration/Static binary code rewriting
                                                            Edited Header
                                                 Header
• Realization:                                Segment of     Segment of
                                                 code           code
       – With reallocation:
                                              Segment of     Segment of
               • Level of segment;               data           data
               • Level of function;                         Extra segment
                                                               of code
       – Without reallocation.
                                                            Extra segment
                                                                of data
Digital Security                  Positive Hack Days 2012                   26
Static Binary Instrumentation (II)
Reallocation:
1) Function Displacement + Entry Point Linking;
2) Branch Conversion;
3) Instruction Padding;
4) Instrumentation.

  Tools: DynInst, EEL, ATOM, PEBIL, ERESI, TAU,
  Vulcan, BIRD, Aslan(4514N)
Digital Security       Positive Hack Days 2012    27
Debuggers
• Breakpoints:
      •      Software
                                                                      App           Debugger
      •      Hardware

• Debugger + scripting:                                                        OS
      •      WinDBG + pykd
      •      OllyDBG + python = Immunity Debuggers                          Processor
      •      GDB + PythonGDB

• Python library's*: Buggery, IDAPython, ImmLIB, lldb, PyDBG,
  PyDbgEng, pygdb , python-ptrace , vtrace, WinAppDbg, …



      *See “Python Arsenal for Reverse Engineering”


Digital Security                            Positive Hack Days 2012                            28
Dynamic Binary Instrumentation
Dynamic binary instrumentation/Virtual code
  integration/Dynamic binary rewriting
                          DBI
                   App1                    App2


                                OS

                           Processor


Tools: PIN, DynamoRIO, DynInst, Valgrind, BAP,
  KEDR, Fit, ERESI, Detour, Vulcan, SpiderPig
Digital Security     Positive Hack Days 2012      29
Dynamic Binary Instrumentation
• Dynamic Binary Instrumentation (DBI) is a process control and
analysis technique that involves injecting instrumentation code
into a running process.
• Dynamic binary analysis (DBA) tools such as profilers and
checkers help programmers create better software.
• Dynamic binary instrumentation (DBI) frameworks make it easy
to build new DBA tools.

•DBA tools consist:
      – instrumentation routines;
      – analysis routines.



Digital Security                    Positive Hack Days 2012   30
Kinds of DBI
Mode:                               Mode of work:
       – user-mode;                 - Start to finish;
       – kernel-mode.               - Attach.




                                                   Functionality
Modes of execution:                                                JIT

       – Interpretation-mode;
       – Probe-mode;                                                      Probe

       – JIT-mode.                                                 Performance


Digital Security         Positive Hack Days 2012                                  31
DBI Frameworks*
  Frameworks                  OS                    Arch                     Modes      Features
PIN                   Linux,                x86, x86-64,               JIT, Probe    Attach mode
                      Windows,              Itanium, ARM
                      MacOS
DynamoRIO             Linux,                x86, x86-64                JIT, Probe    Runtime
                      Windows                                                        optimization
DynInst               Linux,                x86, x86-64,               Probe         Static &
                      FreeBSD,              ppc32, ARM,                              Dynamic binary
                      Windows               ppc64                                    instrumentation
Valgrind              Linux, MacOS          x86, x86-64,               JIT           IR – VEX,
                                            ppc32, ARM,                              Heavyweight
                                            ppc64                                    DBA tools


      *For more details see “DBI:Intro” presentation from ZeroNights conference

Digital Security                             Positive Hack Days 2012                                32
Start work with DBI




Digital Security         Positive Hack Days 2012   33
Levels of granularity
•    Instruction;
•    Basic Block*;
•    Trace/Superblock;
•    Function;
•    Section;
•    Events;
•    Binary image.

Digital Security          Positive Hack Days 2012   34
Self-modifying code & DBI
Detect:
       – Written-protecting code pages
       – Checking store address
       – Inserting extra code




Digital Security            Positive Hack Days 2012   35
Overhead
                           O=X+Y
                           Y = N*Z
                           Z = K+L

O – Tool Overhead;
X – Instrumentation Routines Overhead;
Y – Analysis Routines Overhead;
N – Frequency of Calling Analysis Routine;
Z – Work Performed in the Analysis Routine;
K – Work Required to Transition to Analysis Routine;
L – Work Performed Inside the Analysis Routine.

Digital Security         Positive Hack Days 2012       36
Rewriting instructions
• Platforms:
       – with fixed-length instruction;
       – with variable-length instructions.




Digital Security           Positive Hack Days 2012   37
Rewriting code (I)
• Easy / simple / boring / regular example
       – Rewriting prolog function




Digital Security          Positive Hack Days 2012   38
Rewriting code (II)
• Hardcore example:
       – Mobile phone firmware rewriting

                                      Bootloader
                   reboot

                                                                    Flash


                            SHELLCODE 1                       AMSS
                                                                                  Malicious SMS
                                                                        GSM


                                                                            Baseband processor
Digital Security                          Positive Hack Days 2012                                 39
Instrumentation in ARM
ARM modes:
       – ARM
               • Length(instr) = 4 byte
       – Thumb
               • Length(instr) = 2 byte
       – Thumb2
               • Length(instr) = 2/4 byte
       – Jazzle



       For more detail see “A Dynamic Binary Instrumentation Engine for the ARM
          Architecture” presentation.

Digital Security                          Positive Hack Days 2012                 40
Emulation


                   App1                        OS


                           Emulator

                               OS

                          Processor




Digital Security     Positive Hack Days 2012        41
Instrumentation & Bochs
• Bochs can be called with instrumentation support.


• C++ callbacks occur when certain events happen:
       –     Poweron/Reset/Shutdown;
       –     Branch Taken/Not Taken/Unconditional;
       –     Opcode Decode (All relevant fields, lengths);
       –     Interrupt /Exception;
       –     Cache /TLB Flush/Prefetch;
       –     Memory Read/Write.

• “bochs-python-instrumentation” patch by Ero Carrera

Digital Security                   Positive Hack Days 2012   42
Virtualization

                                                                   App1               OS

               App1                OS
                                                                           VMM

                        VMM                                                  OS

                      Processor                                           Processor

                      Native VMM                                      Hosted VMM


        *VMM - Virtual Machine Monitor

Digital Security                         Positive Hack Days 2012                           43
Instrumentation & virtualization
Stages:
1. Save the VM-exit reason information in the VMCS;
2. Save guest context information;
3. Load the host-state area;
4. Transfer control to the hypervisor;
5. Run own code.



*VMCS - Virtual Machine Control Structure


Digital Security                Positive Hack Days 2012   44
Instrumentation in
                                Mobile World


               Mobile Platform        Language              Executable file format
                   Android                Java                       Dex
                     iOS             Objective-C                   Mach-O
               Windows Phone              .NET                       PE




Digital Security                  Positive Hack Days 2012                            45
Conclusion




One can implement instrumentation of everything!




 Digital Security     Positive Hack Days 2012   46
Contact



Twitter: @evdokimovds
E-mail: d.evdokimov@dsecrg.com




Digital Security   Positive Hack Days 2012   47

Weitere ähnliche Inhalte

Andere mochten auch

Bci for Beginners
Bci for BeginnersBci for Beginners
Bci for BeginnersIainLewis
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentationMennan Tekbir
 
Positive Hack Days. Christopher Gould. Head in the Clouds…Can we overcome sec...
Positive Hack Days. Christopher Gould. Head in the Clouds…Can we overcome sec...Positive Hack Days. Christopher Gould. Head in the Clouds…Can we overcome sec...
Positive Hack Days. Christopher Gould. Head in the Clouds…Can we overcome sec...Positive Hack Days
 
Анализ работы антивирусных лабораторий
Анализ работы антивирусных лабораторийАнализ работы антивирусных лабораторий
Анализ работы антивирусных лабораторийPositive Hack Days
 
رويكردهاي متداول در مديريت استعدادها
رويكردهاي متداول در مديريت استعدادها  رويكردهاي متداول در مديريت استعدادها
رويكردهاي متداول در مديريت استعدادها digidanesh
 
Ops for NoOps - Operational Challenges for Serverless Apps
Ops for NoOps - Operational Challenges for Serverless AppsOps for NoOps - Operational Challenges for Serverless Apps
Ops for NoOps - Operational Challenges for Serverless AppsErica Windisch
 
Positive Hack Days. Gritsai. VOIP insecurities workshop
Positive Hack Days. Gritsai. VOIP insecurities workshopPositive Hack Days. Gritsai. VOIP insecurities workshop
Positive Hack Days. Gritsai. VOIP insecurities workshopPositive Hack Days
 
Positive Hack Days. Gurzov. VOIP - Reduce Your Expenses, Increase Your Income...
Positive Hack Days. Gurzov. VOIP - Reduce Your Expenses, Increase Your Income...Positive Hack Days. Gurzov. VOIP - Reduce Your Expenses, Increase Your Income...
Positive Hack Days. Gurzov. VOIP - Reduce Your Expenses, Increase Your Income...Positive Hack Days
 
Docker in 30 minutes
Docker in 30 minutesDocker in 30 minutes
Docker in 30 minutesSteve Poole
 
Бинарный анализ с декомпиляцией и LLVM
Бинарный анализ с декомпиляцией и LLVMБинарный анализ с декомпиляцией и LLVM
Бинарный анализ с декомпиляцией и LLVMPositive Hack Days
 
Monitoring Containers with Weave Scope
Monitoring Containers with Weave ScopeMonitoring Containers with Weave Scope
Monitoring Containers with Weave ScopeWeaveworks
 

Andere mochten auch (11)

Bci for Beginners
Bci for BeginnersBci for Beginners
Bci for Beginners
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentation
 
Positive Hack Days. Christopher Gould. Head in the Clouds…Can we overcome sec...
Positive Hack Days. Christopher Gould. Head in the Clouds…Can we overcome sec...Positive Hack Days. Christopher Gould. Head in the Clouds…Can we overcome sec...
Positive Hack Days. Christopher Gould. Head in the Clouds…Can we overcome sec...
 
Анализ работы антивирусных лабораторий
Анализ работы антивирусных лабораторийАнализ работы антивирусных лабораторий
Анализ работы антивирусных лабораторий
 
رويكردهاي متداول در مديريت استعدادها
رويكردهاي متداول در مديريت استعدادها  رويكردهاي متداول در مديريت استعدادها
رويكردهاي متداول در مديريت استعدادها
 
Ops for NoOps - Operational Challenges for Serverless Apps
Ops for NoOps - Operational Challenges for Serverless AppsOps for NoOps - Operational Challenges for Serverless Apps
Ops for NoOps - Operational Challenges for Serverless Apps
 
Positive Hack Days. Gritsai. VOIP insecurities workshop
Positive Hack Days. Gritsai. VOIP insecurities workshopPositive Hack Days. Gritsai. VOIP insecurities workshop
Positive Hack Days. Gritsai. VOIP insecurities workshop
 
Positive Hack Days. Gurzov. VOIP - Reduce Your Expenses, Increase Your Income...
Positive Hack Days. Gurzov. VOIP - Reduce Your Expenses, Increase Your Income...Positive Hack Days. Gurzov. VOIP - Reduce Your Expenses, Increase Your Income...
Positive Hack Days. Gurzov. VOIP - Reduce Your Expenses, Increase Your Income...
 
Docker in 30 minutes
Docker in 30 minutesDocker in 30 minutes
Docker in 30 minutes
 
Бинарный анализ с декомпиляцией и LLVM
Бинарный анализ с декомпиляцией и LLVMБинарный анализ с декомпиляцией и LLVM
Бинарный анализ с декомпиляцией и LLVM
 
Monitoring Containers with Weave Scope
Monitoring Containers with Weave ScopeMonitoring Containers with Weave Scope
Monitoring Containers with Weave Scope
 

Ähnlich wie Light And Dark Side Of Code Instrumentation

Dmitriy evdokimov. light and dark side of code instrumentation
Dmitriy evdokimov. light and dark side of code instrumentationDmitriy evdokimov. light and dark side of code instrumentation
Dmitriy evdokimov. light and dark side of code instrumentationYury Chemerkin
 
CYBER INTELLIGENCE & RESPONSE TECHNOLOGY
CYBER INTELLIGENCE & RESPONSE TECHNOLOGYCYBER INTELLIGENCE & RESPONSE TECHNOLOGY
CYBER INTELLIGENCE & RESPONSE TECHNOLOGYjmical
 
Bypass Security Checking with Frida
Bypass Security Checking with FridaBypass Security Checking with Frida
Bypass Security Checking with FridaSatria Ady Pradana
 
Neil Tompson - SoftTest Ireland
Neil Tompson - SoftTest IrelandNeil Tompson - SoftTest Ireland
Neil Tompson - SoftTest IrelandDavid O'Dowd
 
Security and Mobile Application Management with Worklight
Security and Mobile Application Management with WorklightSecurity and Mobile Application Management with Worklight
Security and Mobile Application Management with WorklightIBM WebSphereIndia
 
PIRATEs of the Software Supply Chain.pdf
PIRATEs of the Software Supply Chain.pdfPIRATEs of the Software Supply Chain.pdf
PIRATEs of the Software Supply Chain.pdfTAURUSEER
 
Splunk Overview
Splunk OverviewSplunk Overview
Splunk OverviewSplunk
 
Bypass Security Checking with Frida
Bypass Security Checking with FridaBypass Security Checking with Frida
Bypass Security Checking with FridaSatria Ady Pradana
 
Ibm עמרי וייסמן
Ibm  עמרי וייסמןIbm  עמרי וייסמן
Ibm עמרי וייסמןlihig
 
Omri
OmriOmri
Omrilihig
 
Ibm עמרי וייסמן
Ibm  עמרי וייסמןIbm  עמרי וייסמן
Ibm עמרי וייסמןlihig
 
McAffee_Security and System Integrity in Embedded Devices
McAffee_Security and System Integrity in Embedded DevicesMcAffee_Security and System Integrity in Embedded Devices
McAffee_Security and System Integrity in Embedded DevicesIşınsu Akçetin
 
DSS ITSEC Conference 2012 - SIEM Q1 Labs IBM Security Systems Intelligence
DSS ITSEC Conference 2012 - SIEM Q1 Labs IBM Security Systems IntelligenceDSS ITSEC Conference 2012 - SIEM Q1 Labs IBM Security Systems Intelligence
DSS ITSEC Conference 2012 - SIEM Q1 Labs IBM Security Systems IntelligenceAndris Soroka
 
How to make money out of open source software?
How to make money out of open source software?How to make money out of open source software?
How to make money out of open source software?SANGHEE SHIN
 
Symantec Endpoint Protection 12
Symantec Endpoint Protection 12Symantec Endpoint Protection 12
Symantec Endpoint Protection 12Symantec
 

Ähnlich wie Light And Dark Side Of Code Instrumentation (20)

Dmitriy evdokimov. light and dark side of code instrumentation
Dmitriy evdokimov. light and dark side of code instrumentationDmitriy evdokimov. light and dark side of code instrumentation
Dmitriy evdokimov. light and dark side of code instrumentation
 
CYBER INTELLIGENCE & RESPONSE TECHNOLOGY
CYBER INTELLIGENCE & RESPONSE TECHNOLOGYCYBER INTELLIGENCE & RESPONSE TECHNOLOGY
CYBER INTELLIGENCE & RESPONSE TECHNOLOGY
 
iScan Online - PCI DSS Mobile Task Force
iScan Online - PCI DSS Mobile Task ForceiScan Online - PCI DSS Mobile Task Force
iScan Online - PCI DSS Mobile Task Force
 
RTF - Prasad bhatt
RTF - Prasad bhattRTF - Prasad bhatt
RTF - Prasad bhatt
 
Bypass Security Checking with Frida
Bypass Security Checking with FridaBypass Security Checking with Frida
Bypass Security Checking with Frida
 
Neil Tompson - SoftTest Ireland
Neil Tompson - SoftTest IrelandNeil Tompson - SoftTest Ireland
Neil Tompson - SoftTest Ireland
 
Security and Mobile Application Management with Worklight
Security and Mobile Application Management with WorklightSecurity and Mobile Application Management with Worklight
Security and Mobile Application Management with Worklight
 
PIRATEs of the Software Supply Chain.pdf
PIRATEs of the Software Supply Chain.pdfPIRATEs of the Software Supply Chain.pdf
PIRATEs of the Software Supply Chain.pdf
 
Minesoft Presentation
Minesoft PresentationMinesoft Presentation
Minesoft Presentation
 
Splunk Overview
Splunk OverviewSplunk Overview
Splunk Overview
 
Bypass Security Checking with Frida
Bypass Security Checking with FridaBypass Security Checking with Frida
Bypass Security Checking with Frida
 
Ibm עמרי וייסמן
Ibm  עמרי וייסמןIbm  עמרי וייסמן
Ibm עמרי וייסמן
 
Omri
OmriOmri
Omri
 
Ibm עמרי וייסמן
Ibm  עמרי וייסמןIbm  עמרי וייסמן
Ibm עמרי וייסמן
 
McAffee_Security and System Integrity in Embedded Devices
McAffee_Security and System Integrity in Embedded DevicesMcAffee_Security and System Integrity in Embedded Devices
McAffee_Security and System Integrity in Embedded Devices
 
ESET on cybersecurity.
ESET on cybersecurity.ESET on cybersecurity.
ESET on cybersecurity.
 
DSS ITSEC Conference 2012 - SIEM Q1 Labs IBM Security Systems Intelligence
DSS ITSEC Conference 2012 - SIEM Q1 Labs IBM Security Systems IntelligenceDSS ITSEC Conference 2012 - SIEM Q1 Labs IBM Security Systems Intelligence
DSS ITSEC Conference 2012 - SIEM Q1 Labs IBM Security Systems Intelligence
 
How to make money out of open source software?
How to make money out of open source software?How to make money out of open source software?
How to make money out of open source software?
 
Symantec Endpoint Protection 12
Symantec Endpoint Protection 12Symantec Endpoint Protection 12
Symantec Endpoint Protection 12
 
Android and Intel Inside
Android and Intel InsideAndroid and Intel Inside
Android and Intel Inside
 

Mehr von Positive Hack Days

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesPositive Hack Days
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerPositive Hack Days
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesPositive Hack Days
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikPositive Hack Days
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQubePositive Hack Days
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityPositive Hack Days
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Positive Hack Days
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для ApproofPositive Hack Days
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Positive Hack Days
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложенийPositive Hack Days
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложенийPositive Hack Days
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application SecurityPositive Hack Days
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летPositive Hack Days
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиPositive Hack Days
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОPositive Hack Days
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке СиPositive Hack Days
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CorePositive Hack Days
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опытPositive Hack Days
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterPositive Hack Days
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиPositive Hack Days
 

Mehr von Positive Hack Days (20)

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release Notes
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows Docker
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive Technologies
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + Qlik
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQube
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps Community
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для Approof
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложений
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложений
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application Security
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 лет
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПО
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке Си
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET Core
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опыт
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services Center
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атаки
 

Kürzlich hochgeladen

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Kürzlich hochgeladen (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 

Light And Dark Side Of Code Instrumentation

  • 1. Light and Dark side of Code Instrumentation Dmitriy “D1g1″ Evdokimov DSecRG, Security Researcher
  • 2. #whoami • Security Researcher in DSecRG – RE – Fuzzing – Mobile security • Organizer: DCG #7812 • Editor in “XAKEP” Digital Security Positive Hack Days 2012 2
  • 3. Agenda 1. Instrumentation . 2. Instrumentation .. 3. Instrumentation … 4. Instrumentation …. 5. Instrumentation ….. 6. Instrumentation …… 7. Instrumentation ……. Digital Security Positive Hack Days 2012 3
  • 4. Intro “It has been proved by scientists that a new point of evolution, any technical progress appears when a Man makes up a new type of tool, but not a product.” Digital Security Positive Hack Days 2012 4
  • 5. Instrumentation Instrumentation is a technique adding extra code to an program/environment for monitoring/change some program behavior. Environment Program Program Own Own extra extra code code Digital Security Positive Hack Days 2012 5
  • 6. Why is it necessary? Parallel optimization Simulation Memory debugging Virtualization Emulation Software profiling Performance analysis Testing Automated debugging Correctness checking Error detection Collecting code metrics Binary translation Optimization Memory leak detection Digital Security Positive Hack Days 2012 6
  • 7. Instrumentation in information security Control flow analysis Security test case generation Unpack Code coverage Virtual patching Malware analysis Vulnerability detection Privacy monitoring Taint analysis Antivirus technology Sandboxing Program shepherding Data flow analysis Shellcode detection Deobfuscation Fuzzing Reverse engineering Behavior based security Forensic Transparent debugging Data Structure Restoring Security enforcement Digital Security Positive Hack Days 2012 7
  • 8. Analysis Criterion Static analysis Dynamic analysis Code vs. data Problem No problem Code coverage Big (but not all) One way Information about values No information All information Self-modifying code Problem No problem Interaction with the No Yes environment Unused code Analysis No analysis JIT code Problem No problem Digital Security Positive Hack Days 2012 8
  • 9. Code Discovery Memory After static analysis 0101010110101001010010 Instr 1 After dynamic analysis 0101010101101010101010 Instr 2 Instr 3 1111010101110101000111 jump reg InstrDATA 4 Instr 1011100111001010101011 5 Instr 4 6 Instr Instr 7 5 jmp 0x0ABCD PADDING 0111010110100111100110 Instr 7 cont. Instr 8 1010101101110001001011 Instr 9 Instr 6 10 Instr Digital Security Positive Hack Days 2012 9
  • 10. The general scheme of code instrumentation 1. Find points of instrumentation; 2. Insert instrumentation; 3. Take control from program; 4. Save context of the program; 5. Execute own code; 6. Restore context of the program; 7. Return control to program. Digital Security Positive Hack Days 2012 10
  • 11. Source Data Source data Source code Byte code Binary code Digital Security Positive Hack Days 2012 11
  • 12. Classification of target instrumentation Instrumentation With source code Without source code Source code Byte code Binary code Linker/Compiler Byte code Executable file Interpreter/VM Process Environment Dynamic binary instrumentation Static binary modification Byte code instrumentation Link-time/Compilation-time Source code instrumentation Environment - Static instrumentation Hardware - Load-time Digital- Dynamic Security Positive Hack Days 2012 12
  • 13. Source code instrumentation • Source code* – Source code instrumentation • Manual skills • Plugins for IDE – Link-time/Compilation-time instrumentation • Options of linker/compiler • Tools: Visual Studio Profiler, gcc, TAU, OPARI, Diablo, Phoenix, LLVM, Rational Purify, Valgrind *Unreal condition for security specialist =) Digital Security Positive Hack Days 2012 13
  • 14. Unmoral programming Digital Security Positive Hack Days 2012 14
  • 15. Byte code instrumentation Byte code – intermediate representation between source code and machine code. … Java VM Dalvik VM AVM/AVM2 CLR Digital Security Positive Hack Days 2012 15
  • 16. Instrumentation byte-code (I) Source code Compilation Byte-code Load Virtual machine Loader JIT Lib Execute Lib Lib Machine code Digital Security Positive Hack Days 2012 16
  • 17. Instrumentation byte code (II) • Byte-code – Static instrumentation • Static byte code instrumentation – Load-time instrumentation • Custom byte code loader – Dynamic instrumentation • Dynamic byte code instrumentation Digital Security Positive Hack Days 2012 17
  • 18. Instrumentation Java (I) Mechanisms: • java.lang.instrument package; • Java Platform Debugger Architecture (JPDA) . Digital Security Positive Hack Days 2012 18
  • 19. Instrumentation Java (II) • Static instrumentation – Modification *.class files • Load-time instrumentation – ClassFileLoadHook – Custom ClassLoader • Dynamic instrumentation – ClassFileLoadHook -> RetransformClasses Tools: Javassist, ObjectWeb ASM, BCEL, JOIE, reJ JavaSnoop, Serp, JMangler Digital Security Positive Hack Days 2012 19
  • 20. Instrumentation .NET • Static instrumentation – Modification DLL files • Load-time instrumentation – AppDomain.Load()/Assembly.Load() – Joint redirection – Via event handler Tools: ReFrameworker, MBEL, RAIL, Cecil Digital Security Positive Hack Days 2012 20
  • 21. Instrumentation ActionScript (I) • ActionScript2 – AVM – Tags that (can) contain bytecode: • DefineButton (7), DefineButton2 (34), DefineSprite (39), DoAction (12), DoInitAction (59), PlaceObject2 (26), PlaceObject3 (70). • ActionScript3 – AVM2 – Tags that (can) contain bytecode: • DoABC (82), RawABC (72). Digital Security Positive Hack Days 2012 21
  • 22. AVM2 Architecture AS3 .abc function (x:int):int { return x+10 } .abc parser MIR JIT Compiler .abc @1 arg +8// argv getlocal 1 Verifier Bytecode MIR Code Generator @2 load [@1+4] pushint 10 @3 imm 10 add @4 add (@2,@3) returnvalue Interpreter MD Code Generator @5 ret @4 // @4:eax (x86, PPC, ARM, etc.) x86 Runtime System (Type System, Object Model) mov eax,(eap+8) mov eax,(eax+4) add eax,10 Memory Manager/Garbage Collector ret Digital Security Positive Hack Days 2012 22
  • 23. Instrumentation ActionScript (I) AVM tag Original SWF file Header Tags Instrumenteted SWF file Digital Security Positive Hack Days 2012 23
  • 24. Instrumentation AVM (II) • Static instrumentation – Add : • trace() • dump() • debug() • debugfile() • debugline() – Modification: • Create own class + change class name = hook! Digital Security Positive Hack Days 2012 24
  • 25. Instrumentation binary code • The executable file • Environment – Static code instrumentation – Modifying call table • Static binary instrumentation • IDT, CPU MSRs, GDT, SSDT, • Process IRP тable – Debuggers • … • Debugging API – Modifying OS options – Modifying call table/other structure • SHIM • IAT • LD_PRELOAD • … • AppInt_DLLs – Dynamic code instrumentation • DLL injection • Dynamic binary instrumentation • … • Hardware – Reproduction of the – Hardware debug features environment • Debug registers • Emulation • Hardware debuggers • Virtualization • … Digital Security Positive Hack Days 2012 25
  • 26. Static Binary Instrumentation (I) Static binary instrumentation/Physical code integration/Static binary code rewriting Edited Header Header • Realization: Segment of Segment of code code – With reallocation: Segment of Segment of • Level of segment; data data • Level of function; Extra segment of code – Without reallocation. Extra segment of data Digital Security Positive Hack Days 2012 26
  • 27. Static Binary Instrumentation (II) Reallocation: 1) Function Displacement + Entry Point Linking; 2) Branch Conversion; 3) Instruction Padding; 4) Instrumentation. Tools: DynInst, EEL, ATOM, PEBIL, ERESI, TAU, Vulcan, BIRD, Aslan(4514N) Digital Security Positive Hack Days 2012 27
  • 28. Debuggers • Breakpoints: • Software App Debugger • Hardware • Debugger + scripting: OS • WinDBG + pykd • OllyDBG + python = Immunity Debuggers Processor • GDB + PythonGDB • Python library's*: Buggery, IDAPython, ImmLIB, lldb, PyDBG, PyDbgEng, pygdb , python-ptrace , vtrace, WinAppDbg, … *See “Python Arsenal for Reverse Engineering” Digital Security Positive Hack Days 2012 28
  • 29. Dynamic Binary Instrumentation Dynamic binary instrumentation/Virtual code integration/Dynamic binary rewriting DBI App1 App2 OS Processor Tools: PIN, DynamoRIO, DynInst, Valgrind, BAP, KEDR, Fit, ERESI, Detour, Vulcan, SpiderPig Digital Security Positive Hack Days 2012 29
  • 30. Dynamic Binary Instrumentation • Dynamic Binary Instrumentation (DBI) is a process control and analysis technique that involves injecting instrumentation code into a running process. • Dynamic binary analysis (DBA) tools such as profilers and checkers help programmers create better software. • Dynamic binary instrumentation (DBI) frameworks make it easy to build new DBA tools. •DBA tools consist: – instrumentation routines; – analysis routines. Digital Security Positive Hack Days 2012 30
  • 31. Kinds of DBI Mode: Mode of work: – user-mode; - Start to finish; – kernel-mode. - Attach. Functionality Modes of execution: JIT – Interpretation-mode; – Probe-mode; Probe – JIT-mode. Performance Digital Security Positive Hack Days 2012 31
  • 32. DBI Frameworks* Frameworks OS Arch Modes Features PIN Linux, x86, x86-64, JIT, Probe Attach mode Windows, Itanium, ARM MacOS DynamoRIO Linux, x86, x86-64 JIT, Probe Runtime Windows optimization DynInst Linux, x86, x86-64, Probe Static & FreeBSD, ppc32, ARM, Dynamic binary Windows ppc64 instrumentation Valgrind Linux, MacOS x86, x86-64, JIT IR – VEX, ppc32, ARM, Heavyweight ppc64 DBA tools *For more details see “DBI:Intro” presentation from ZeroNights conference Digital Security Positive Hack Days 2012 32
  • 33. Start work with DBI Digital Security Positive Hack Days 2012 33
  • 34. Levels of granularity • Instruction; • Basic Block*; • Trace/Superblock; • Function; • Section; • Events; • Binary image. Digital Security Positive Hack Days 2012 34
  • 35. Self-modifying code & DBI Detect: – Written-protecting code pages – Checking store address – Inserting extra code Digital Security Positive Hack Days 2012 35
  • 36. Overhead O=X+Y Y = N*Z Z = K+L O – Tool Overhead; X – Instrumentation Routines Overhead; Y – Analysis Routines Overhead; N – Frequency of Calling Analysis Routine; Z – Work Performed in the Analysis Routine; K – Work Required to Transition to Analysis Routine; L – Work Performed Inside the Analysis Routine. Digital Security Positive Hack Days 2012 36
  • 37. Rewriting instructions • Platforms: – with fixed-length instruction; – with variable-length instructions. Digital Security Positive Hack Days 2012 37
  • 38. Rewriting code (I) • Easy / simple / boring / regular example – Rewriting prolog function Digital Security Positive Hack Days 2012 38
  • 39. Rewriting code (II) • Hardcore example: – Mobile phone firmware rewriting Bootloader reboot Flash SHELLCODE 1 AMSS Malicious SMS GSM Baseband processor Digital Security Positive Hack Days 2012 39
  • 40. Instrumentation in ARM ARM modes: – ARM • Length(instr) = 4 byte – Thumb • Length(instr) = 2 byte – Thumb2 • Length(instr) = 2/4 byte – Jazzle For more detail see “A Dynamic Binary Instrumentation Engine for the ARM Architecture” presentation. Digital Security Positive Hack Days 2012 40
  • 41. Emulation App1 OS Emulator OS Processor Digital Security Positive Hack Days 2012 41
  • 42. Instrumentation & Bochs • Bochs can be called with instrumentation support. • C++ callbacks occur when certain events happen: – Poweron/Reset/Shutdown; – Branch Taken/Not Taken/Unconditional; – Opcode Decode (All relevant fields, lengths); – Interrupt /Exception; – Cache /TLB Flush/Prefetch; – Memory Read/Write. • “bochs-python-instrumentation” patch by Ero Carrera Digital Security Positive Hack Days 2012 42
  • 43. Virtualization App1 OS App1 OS VMM VMM OS Processor Processor Native VMM Hosted VMM *VMM - Virtual Machine Monitor Digital Security Positive Hack Days 2012 43
  • 44. Instrumentation & virtualization Stages: 1. Save the VM-exit reason information in the VMCS; 2. Save guest context information; 3. Load the host-state area; 4. Transfer control to the hypervisor; 5. Run own code. *VMCS - Virtual Machine Control Structure Digital Security Positive Hack Days 2012 44
  • 45. Instrumentation in Mobile World Mobile Platform Language Executable file format Android Java Dex iOS Objective-C Mach-O Windows Phone .NET PE Digital Security Positive Hack Days 2012 45
  • 46. Conclusion One can implement instrumentation of everything! Digital Security Positive Hack Days 2012 46