SlideShare a Scribd company logo
© 2015 IBM Corporation
How to cook your own fast and scalable DBI-based security tool. A case study
Exploring billion states of a
program like a pro
2017
© 2015 IBM Corporation
IBM Research - Haifa
About me
 PhD (Tomsk State University of Control Systems and Radioelectronics)
– Vulnerabilities detection in machine code (x86)
 Cyber Security Researcher at IBM Research Lab in Haifa, Israel
– R&D in technologies for highly-evasive malware analysis and detection
 A main contributor to DynamoRIO/DrMemory DBI frameworks
2017
© 2015 IBM Corporation
IBM Research - Haifa
Outline
 Dynamic binary instrumentation technique
– General idea and technique implementation
– DynamoRIO and Intel PIN frameworks comparison
– Possible application fields
 Example I. Heap-based bug detection using DBI
– General idea & motivation
– Implementation & issues
– Solutions for described issues
 Example II. Dynamic malware analysis
– General idea & motivation
– Implementation
– Tool demo
 Conclusion
2017
© 2015 IBM Corporation
IBM Research - Haifa
Dynamic binary instrumentation (DBI)
DBI is a technique of analyzing the behavior of a binary application at runtime through the
injection of instrumentation code
2017
© 2015 IBM Corporation
IBM Research - Haifa
How does it work ?
Application
launcher.exe
core.dll
DBI Engine
CreateProcess (suspended)
(1)
Inject core.dll
(2)
Application in memory
Windows kernel
Takebasicblock
(4)(3)
Hook entry point
core.dll + user dll/dlls
shared system dlls
ins1
ins2
ins3
insN
.
.
Code cache
basic block
transformation
(5)
ins1
inst_ins1
inst_ins2
ins2
inst_ins3
inst_ins4
ins3
inst_ins4
inst_ins5
insN
inst_insM
inst_insM+1
Execute &
calculate
addr of next
basic block
(6)
Takenextbasicblock
(7)
.
.
© 2015 IBM Corporation
IBM Research - Haifa
Frameworks Comparison
DynamoRIO Intel PIN
Redistribution
model
Open-source, BSD – license Proprietary, no-source
code available
Supported
architectures
x86, x86-64, ARM, AArch64 x86, x86-64
Supported
Platforms
Linux, Windows, MacOS,
Android
Linux, Windows, MacOS,
Android
Average
runtime overhead
108% (no tool)
139% (BBs counter)
130% (no tool)
162% (BBs counter)
Language C/C++ C/C++ (some Python
wrappers available)
Technology Binary code transformation callout/trampolines
2017
© 2015 IBM Corporation
IBM Research - Haifa
Instructions Counting. Example
DynamoRIOIntel PIN
2017
© 2015 IBM Corporation
IBM Research - Haifa
Instrumentation Granularity
Instruction level
(instrument all executed instructions)
Basic block level
(instrument all executed basic blocks)
Function call level
(instrument all executed calls)
Module level
(instrument all load/unload module events)
Events
• exceptions/signals
• syscalls
• thread/process creation/deletion
2017
© 2015 IBM Corporation
IBM Research - Haifa
Application
 Software security analysis & testing
– Support fuzzing (code coverage assessment, tainted input tracking)
– Bugs detection (overflows, use-after-free, uninitialized access and etc.)
– Symbolic execution
– Software bugs exploitability assessment
 Malware analysis
– Execution tracing
– Automatic unpacking
 Reverse-engineering
– Control-flow graph visualization
– Debugging
– Taint-tracking
 Other non-security fields
– Performance evaluation
– Memory leak detection
– Optimization
2017
© 2015 IBM Corporation
IBM Research - Haifa
Example I. Bugs detection
2017
© 2015 IBM Corporation
IBM Research - Haifa
WinHeap Explorer Tool
 WinHeap Explorer is a system for heap-based bug detection with the lowest runtime
overhead build on top of Intel PIN framework.
 Advantages:
– Light-weight instrumentation support (shown further)
– Lowest runtime-overhead
– Open-source (BSD license)
2017
© 2015 IBM Corporation
IBM Research - Haifa
Motivation Example
2017
© 2015 IBM Corporation
IBM Research - Haifa
Motivation Example
2017
© 2015 IBM Corporation
IBM Research - Haifa
Motivation Example
Heap memory block for a
Heap Layout
pMethod 1 pMethod 2 pMethod 3 pMethod 4
Virtual table for pFileOpen
2017
© 2015 IBM Corporation
IBM Research - Haifa
Motivation Example
Heap memory block for a pEvilMet 1 pMethod 2 pMethod 3 pMethod 4
Virtual table for pFileOpen
Heap Layout
2017
© 2015 IBM Corporation
IBM Research - Haifa
Detection of Heap-based Bugs. General Idea
Code Heap
instruction #1
instruction #2
instruction #3
instruction #4
instruction #5
0x0 – 0x3
0x4 – 0x7
0x8 – 0xB
0xC – 0xF
0x10 – 0x13
0x14 – 0x17
0x80 – 0x83
0x84 – 0x87
0x88 – 0x8B
0x8C – 0x8F
0x90 – 0x93
0x94 – 0x98
…
2017
© 2015 IBM Corporation
IBM Research - Haifa
Detection of Heap-based Bugs. General Idea
Code Heap
instruction #1
instruction #2
instruction #3
instruction #4
instruction #5
0x0 – 0x3
0x4 – 0x7
0x8 – 0xB
0xC – 0xF
0x10 – 0x13
0x14 – 0x17
0x80 – 0x83
0x84 – 0x87
0x88 – 0x8B
0x8C – 0x8F
0x90 – 0x93
0x94 – 0x98
…
Allocated
memory
block #1
Freed
memory
block #2
2017
© 2015 IBM Corporation
IBM Research - Haifa
Detection of Heap-based Bugs. General Idea
Code
Correct instruction #1
Correct instruction #2
Incorrect instruction #3
Incorrect instruction #4
Incorrect instruction #5
[overflow]
[access block #1]
[access block #1]
[underflow]
[use after free]
Heap
0x0 – 0x3
0x4 – 0x7
0x8 – 0xB
0xC – 0xF
0x10 – 0x13
0x14 – 0x17
0x80 – 0x83
0x84 – 0x87
0x88 – 0x8B
0x8C – 0x8F
0x90 – 0x93
0x94 – 0x98
…
Allocated
memory
block #1
Freed
memory
block #2
2017
© 2015 IBM Corporation
IBM Research - Haifa
Detection of Heap-based Bugs. General Idea
Code
Correct instruction #1
Correct instruction #2
Incorrect instruction #3
Incorrect instruction #4
Incorrect instruction #5
[overflow]
[access block #1]
[access block #1]
[underflow]
[use after free]
Heap
0x0 – 0x3
0x4 – 0x7
0x8 – 0xB
0xC – 0xF
0x10 – 0x13
0x14 – 0x17
0x80 – 0x83
0x84 – 0x87
0x88 – 0x8B
0x8C – 0x8F
0x90 – 0x93
0x94 – 0x98
…
Allocated
memory
block #1
Freed
memory
block #2
redzone
redzone
marked as freed
2017
© 2015 IBM Corporation
IBM Research - Haifa
Detection of Heap-based Bugs. General Idea
Code
Correct instruction #1
Correct instruction #2
Incorrect instruction #3
Incorrect instruction #4
Incorrect instruction #5
[overflow]
[access block #1]
[access block #1]
[underflow]
[use after free]
Heap
0x0 – 0x3
0x4 – 0x7
0x8 – 0xB
0xC – 0xF
0x10 – 0x13
0x14 – 0x17
0x80 – 0x83
0x84 – 0x87
0x88 – 0x8B
0x8C – 0x8F
0x90 – 0x93
0x94 – 0x98
…
Allocated
memory
block #1
Freed
memory
block #2
redzone
redzone
marked as freed
𝑖𝑓 𝑝𝑜𝑖𝑛𝑡𝑒𝑟 ∈ 𝑟𝑒𝑑𝑧𝑜𝑛𝑒 𝑜𝑟 𝑝𝑜𝑖𝑛𝑡𝑒𝑟 ∈ 𝑓𝑟𝑒𝑒𝑑 𝑡ℎ𝑒𝑛 𝒃𝒖𝒈
2017
© 2015 IBM Corporation
IBM Research - Haifa
Detection of Heap-based Bugs. General Idea
Code
Correct instruction #1
Correct instruction #2
Incorrect instruction #3
Incorrect instruction #4
Incorrect instruction #5
[overflow]
[access block #1]
[access block #1]
[underflow]
[use after free]
Heap
0x0 – 0x3
0x4 – 0x7
0x8 – 0xB
0xC – 0xF
0x10 – 0x13
0x14 – 0x17
0x80 – 0x83
0x84 – 0x87
0x88 – 0x8B
0x8C – 0x8F
0x90 – 0x93
0x94 – 0x98
…
Allocated
memory
block #1
Freed
memory
block #2
redzone
redzone
marked as freed
2017
© 2015 IBM Corporation
IBM Research - Haifa
WinHeap Explorer. Implementation #1
Step 1. Instrument all heap management API calls (allocation/reallocation/freeing)
Step 2. Save redzones and heap block statuses (freed or in use) in a hashtable
Step 3. Instrument all executed instructions, dynamically check that an instruction doesn’t
access redzone or previously freed memory block
2017
© 2015 IBM Corporation
IBM Research - Haifa
WinHeap Explorer. Implementation #1
Step 1. Instrument all heap management API calls (allocation/reallocation/freeing)
Step 2. Save redzones and heap block statuses (freed or in use) in a hashtable
Step 3. Instrument all executed instructions, dynamically check that an instruction doesn’t
access redzone or previously freed memory block.
Results:
 Runtime overhead: x310-x850
– Launching Mozilla Firefox = ~498M instructions (or 8 minutes to show first window)
– Launching Acrobat Reader = ~84M instructions (or 3 minutes to show first window)
– Launching PowerPoint = ~860M instructions (or 12 minutes to show first window)
 Memory overhead: x90-x120
2017
© 2015 IBM Corporation
IBM Research - Haifa
WinHeap Explorer. Implementation #1
Step 1. Instrument all heap management API calls (allocation/reallocation/freeing)
Step 2. Save redzones and heap block statuses (freed or in use) in a hashtable
Step 3. Instrument all executed instructions, dynamically check that an instruction doesn’t
access redzone or previously freed memory block.
Results:
 Runtime overhead: x310-x850
– Launching Mozilla Firefox = ~498M instructions (or 8 minutes to show first window)
– Launching Acrobat Reader = ~84M instructions (or 3 minutes to show first window)
– Launching PowerPoint = ~860M instructions (or 12 minutes to show first window)
 Memory overhead: x90-x120
Absolutely unacceptable
2017
© 2015 IBM Corporation
IBM Research - Haifa
Shadow Memory Approach
2017
© 2015 IBM Corporation
IBM Research - Haifa
Windows Heap Management APIs Architecture
kernel32.dll
HeapAlloc
GlobalAlloc
LocalAlloc
Memory allocation
msvcr*.dll
malloc
calloc
new []
ole32.dll
CoTaskMemAlloc
kernel32.dll
HeapReAlloc
GlobalReAlloc
LocalReAlloc
Memory reallocation
msvcr*.dll
realloc
ole32.dll
CoTaskMemrealloc
kernel32.dll
HeapFree
GlobalFree
LocalFree
Memory freeing
msvcr*.dll
free
delete []
ole32.dll
CoTaskMemFree
ntdll.dll
RtlAllocateHeap RtlReAllocateHeap RtlFreeHeap
Windows Kernel
2017
© 2015 IBM Corporation
IBM Research - Haifa
Light-weight instrumentation. System DLLs instrumentation
2017
© 2015 IBM Corporation
IBM Research - Haifa
Light-weight instrumentation. Whole System Architecture
2017
© 2015 IBM Corporation
IBM Research - Haifa
WinHeap Explorer. Runtime overhead #2
2017
© 2015 IBM Corporation
IBM Research - Haifa
Example 2. Malware analysis
2017
© 2015 IBM Corporation
IBM Research - Haifa
Dynamic Malware Analysis. Motivation
2017
© 2015 IBM Corporation
IBM Research - Haifa
Dynamic Malware Analysis. Motivation
2017
© 2015 IBM Corporation
IBM Research - Haifa
Dynamic Malware Analysis. Idea & Solution
 Goal – transparently and efficiently trace malware’s library calls
 Solution
– Instrument calls to exported library functions
– Print a trace of each executed function along with some arguments information
– Print a return address of each executed function (to be able to recognize calls from
unpacked code)
2017
© 2015 IBM Corporation
IBM Research - Haifa
DrLtrace Tool
 DrLtrace is a standalone application for transparent API calls tracing build on top of
DynamoRIO framework.
 Benefits:
– Transparent (no API-hooking, no debugging)
– High visibility (each API call, all arguments)
– Open-source (BSD license)
– Supported Windows, Linux, Android
– Easy to use, just specify:
drltrace.exe –logdir <log_name> -- <app_name>
2017
© 2015 IBM Corporation
IBM Research - Haifa
Output Examples
2017
© 2015 IBM Corporation
IBM Research - Haifa
DEMO
2017
© 2015 IBM Corporation
IBM Research - Haifa
Conclusion
 DBI is a powerful technique for transparent and efficient machine code introspection
 Numerous possible ways to use, especially for software security analysis, dynamic malware
introspection, reverse-engineering and etc.
 Traditional fast and scalable data structures may introduce significant overhead in case of
DBI
 Two open-source tools were introduced:
– WinHeap Explorer – a tool for heap-based bug detection in Windows applications
– Dr.Ltrace – a tool for transparent dynamic library calls tracing
2017
© 2015 IBM Corporation
IBM Research - Haifa
Links
 WinHeapExplorer – https://github.com/WinHeapExplorer/WinHeap-Explorer
 DrLtrace 1 - https://github.com/DynamoRIO/drmemory/tree/master/drltrace
 Whitepaper - https://github.com/WinHeapExplorer/WinHeap-Explorer/tree/master/PHD
1 – please build from source code to have the latest functionality
2017
© 2015 IBM Corporation
IBM Research - Haifa
Thank you for you attention!
PhD, Research Staff Member
(Cyber Security)
IBM Research Israel
Maksim Shudrak
maksims@il.ibm.com
mxmssh@gmail.com
2017

More Related Content

Similar to Exploring billion states of a program like a pro. How to cook your own fast and scalable DBI-based security tool. A case study.

Flash security past_present_future_final_en
Flash security past_present_future_final_enFlash security past_present_future_final_en
Flash security past_present_future_final_en
Sunghun Kim
 
Inception: A reverse-engineer horror History
Inception: A reverse-engineer horror HistoryInception: A reverse-engineer horror History
Inception: A reverse-engineer horror History
Nelson Brito
 
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Maksim Shudrak
 
LJC-Unconference-2023-Keynote.pdf
LJC-Unconference-2023-Keynote.pdfLJC-Unconference-2023-Keynote.pdf
LJC-Unconference-2023-Keynote.pdf
EmilyJiang23
 
Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...
Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...
Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...
Maksim Shudrak
 
Sensepost assessment automation
Sensepost assessment automationSensepost assessment automation
Sensepost assessment automation
SensePost
 
Deep Exploit@Black Hat Europe 2018 Arsenal
Deep Exploit@Black Hat Europe 2018 ArsenalDeep Exploit@Black Hat Europe 2018 Arsenal
Deep Exploit@Black Hat Europe 2018 Arsenal
Isao Takaesu
 
Software Security : From school to reality and back!
Software Security : From school to reality and back!Software Security : From school to reality and back!
Software Security : From school to reality and back!
Peter Hlavaty
 
Understanding & analyzing obfuscated malicious web scripts by Vikram Kharvi
Understanding & analyzing obfuscated malicious web scripts by Vikram KharviUnderstanding & analyzing obfuscated malicious web scripts by Vikram Kharvi
Understanding & analyzing obfuscated malicious web scripts by Vikram Kharvi
Cysinfo Cyber Security Community
 
A165 tools for java and javascript
A165 tools for java and javascriptA165 tools for java and javascript
A165 tools for java and javascript
Toby Corbin
 
JavaOne 2014: Java Debugging
JavaOne 2014: Java DebuggingJavaOne 2014: Java Debugging
JavaOne 2014: Java DebuggingChris Bailey
 
01 Metasploit kung fu introduction
01 Metasploit kung fu introduction01 Metasploit kung fu introduction
01 Metasploit kung fu introduction
Mostafa Abdel-sallam
 
S016576 managing-data-footprint-reduction-brazil-v1708f
S016576 managing-data-footprint-reduction-brazil-v1708fS016576 managing-data-footprint-reduction-brazil-v1708f
S016576 managing-data-footprint-reduction-brazil-v1708f
Tony Pearson
 
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbersDefcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbersAlexandre Moneger
 
BriMor Labs Live Response Collection - OSDFCON
BriMor Labs Live Response Collection - OSDFCONBriMor Labs Live Response Collection - OSDFCON
BriMor Labs Live Response Collection - OSDFCON
BriMorLabs
 
Comment améliorer le quotidien des Développeurs PHP ?
Comment améliorer le quotidien des Développeurs PHP ?Comment améliorer le quotidien des Développeurs PHP ?
Comment améliorer le quotidien des Développeurs PHP ?
AFUP_Limoges
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOpsOmid Vahdaty
 
Machine learning in cybersecutiry
Machine learning in cybersecutiryMachine learning in cybersecutiry
Machine learning in cybersecutiry
Vishwas N
 
Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...
Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...
Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...
Mobodexter
 
Sandbox detection: leak, abuse, test - Hacktivity 2015
Sandbox detection: leak, abuse, test - Hacktivity 2015Sandbox detection: leak, abuse, test - Hacktivity 2015
Sandbox detection: leak, abuse, test - Hacktivity 2015
Zoltan Balazs
 

Similar to Exploring billion states of a program like a pro. How to cook your own fast and scalable DBI-based security tool. A case study. (20)

Flash security past_present_future_final_en
Flash security past_present_future_final_enFlash security past_present_future_final_en
Flash security past_present_future_final_en
 
Inception: A reverse-engineer horror History
Inception: A reverse-engineer horror HistoryInception: A reverse-engineer horror History
Inception: A reverse-engineer horror History
 
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
 
LJC-Unconference-2023-Keynote.pdf
LJC-Unconference-2023-Keynote.pdfLJC-Unconference-2023-Keynote.pdf
LJC-Unconference-2023-Keynote.pdf
 
Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...
Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...
Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...
 
Sensepost assessment automation
Sensepost assessment automationSensepost assessment automation
Sensepost assessment automation
 
Deep Exploit@Black Hat Europe 2018 Arsenal
Deep Exploit@Black Hat Europe 2018 ArsenalDeep Exploit@Black Hat Europe 2018 Arsenal
Deep Exploit@Black Hat Europe 2018 Arsenal
 
Software Security : From school to reality and back!
Software Security : From school to reality and back!Software Security : From school to reality and back!
Software Security : From school to reality and back!
 
Understanding & analyzing obfuscated malicious web scripts by Vikram Kharvi
Understanding & analyzing obfuscated malicious web scripts by Vikram KharviUnderstanding & analyzing obfuscated malicious web scripts by Vikram Kharvi
Understanding & analyzing obfuscated malicious web scripts by Vikram Kharvi
 
A165 tools for java and javascript
A165 tools for java and javascriptA165 tools for java and javascript
A165 tools for java and javascript
 
JavaOne 2014: Java Debugging
JavaOne 2014: Java DebuggingJavaOne 2014: Java Debugging
JavaOne 2014: Java Debugging
 
01 Metasploit kung fu introduction
01 Metasploit kung fu introduction01 Metasploit kung fu introduction
01 Metasploit kung fu introduction
 
S016576 managing-data-footprint-reduction-brazil-v1708f
S016576 managing-data-footprint-reduction-brazil-v1708fS016576 managing-data-footprint-reduction-brazil-v1708f
S016576 managing-data-footprint-reduction-brazil-v1708f
 
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbersDefcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
 
BriMor Labs Live Response Collection - OSDFCON
BriMor Labs Live Response Collection - OSDFCONBriMor Labs Live Response Collection - OSDFCON
BriMor Labs Live Response Collection - OSDFCON
 
Comment améliorer le quotidien des Développeurs PHP ?
Comment améliorer le quotidien des Développeurs PHP ?Comment améliorer le quotidien des Développeurs PHP ?
Comment améliorer le quotidien des Développeurs PHP ?
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOps
 
Machine learning in cybersecutiry
Machine learning in cybersecutiryMachine learning in cybersecutiry
Machine learning in cybersecutiry
 
Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...
Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...
Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...
 
Sandbox detection: leak, abuse, test - Hacktivity 2015
Sandbox detection: leak, abuse, test - Hacktivity 2015Sandbox detection: leak, abuse, test - Hacktivity 2015
Sandbox detection: leak, abuse, test - Hacktivity 2015
 

Recently uploaded

Announcement of 18th IEEE International Conference on Software Testing, Verif...
Announcement of 18th IEEE International Conference on Software Testing, Verif...Announcement of 18th IEEE International Conference on Software Testing, Verif...
Announcement of 18th IEEE International Conference on Software Testing, Verif...
Sebastiano Panichella
 
Competition and Regulation in Professional Services – KLEINER – June 2024 OEC...
Competition and Regulation in Professional Services – KLEINER – June 2024 OEC...Competition and Regulation in Professional Services – KLEINER – June 2024 OEC...
Competition and Regulation in Professional Services – KLEINER – June 2024 OEC...
OECD Directorate for Financial and Enterprise Affairs
 
Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...
Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...
Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...
Orkestra
 
0x01 - Newton's Third Law: Static vs. Dynamic Abusers
0x01 - Newton's Third Law:  Static vs. Dynamic Abusers0x01 - Newton's Third Law:  Static vs. Dynamic Abusers
0x01 - Newton's Third Law: Static vs. Dynamic Abusers
OWASP Beja
 
Bitcoin Lightning wallet and tic-tac-toe game XOXO
Bitcoin Lightning wallet and tic-tac-toe game XOXOBitcoin Lightning wallet and tic-tac-toe game XOXO
Bitcoin Lightning wallet and tic-tac-toe game XOXO
Matjaž Lipuš
 
Acorn Recovery: Restore IT infra within minutes
Acorn Recovery: Restore IT infra within minutesAcorn Recovery: Restore IT infra within minutes
Acorn Recovery: Restore IT infra within minutes
IP ServerOne
 
Getting started with Amazon Bedrock Studio and Control Tower
Getting started with Amazon Bedrock Studio and Control TowerGetting started with Amazon Bedrock Studio and Control Tower
Getting started with Amazon Bedrock Studio and Control Tower
Vladimir Samoylov
 
Obesity causes and management and associated medical conditions
Obesity causes and management and associated medical conditionsObesity causes and management and associated medical conditions
Obesity causes and management and associated medical conditions
Faculty of Medicine And Health Sciences
 
Eureka, I found it! - Special Libraries Association 2021 Presentation
Eureka, I found it! - Special Libraries Association 2021 PresentationEureka, I found it! - Special Libraries Association 2021 Presentation
Eureka, I found it! - Special Libraries Association 2021 Presentation
Access Innovations, Inc.
 
Bonzo subscription_hjjjjjjjj5hhhhhhh_2024.pdf
Bonzo subscription_hjjjjjjjj5hhhhhhh_2024.pdfBonzo subscription_hjjjjjjjj5hhhhhhh_2024.pdf
Bonzo subscription_hjjjjjjjj5hhhhhhh_2024.pdf
khadija278284
 
International Workshop on Artificial Intelligence in Software Testing
International Workshop on Artificial Intelligence in Software TestingInternational Workshop on Artificial Intelligence in Software Testing
International Workshop on Artificial Intelligence in Software Testing
Sebastiano Panichella
 
somanykidsbutsofewfathers-140705000023-phpapp02.pptx
somanykidsbutsofewfathers-140705000023-phpapp02.pptxsomanykidsbutsofewfathers-140705000023-phpapp02.pptx
somanykidsbutsofewfathers-140705000023-phpapp02.pptx
Howard Spence
 
Doctoral Symposium at the 17th IEEE International Conference on Software Test...
Doctoral Symposium at the 17th IEEE International Conference on Software Test...Doctoral Symposium at the 17th IEEE International Conference on Software Test...
Doctoral Symposium at the 17th IEEE International Conference on Software Test...
Sebastiano Panichella
 

Recently uploaded (13)

Announcement of 18th IEEE International Conference on Software Testing, Verif...
Announcement of 18th IEEE International Conference on Software Testing, Verif...Announcement of 18th IEEE International Conference on Software Testing, Verif...
Announcement of 18th IEEE International Conference on Software Testing, Verif...
 
Competition and Regulation in Professional Services – KLEINER – June 2024 OEC...
Competition and Regulation in Professional Services – KLEINER – June 2024 OEC...Competition and Regulation in Professional Services – KLEINER – June 2024 OEC...
Competition and Regulation in Professional Services – KLEINER – June 2024 OEC...
 
Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...
Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...
Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...
 
0x01 - Newton's Third Law: Static vs. Dynamic Abusers
0x01 - Newton's Third Law:  Static vs. Dynamic Abusers0x01 - Newton's Third Law:  Static vs. Dynamic Abusers
0x01 - Newton's Third Law: Static vs. Dynamic Abusers
 
Bitcoin Lightning wallet and tic-tac-toe game XOXO
Bitcoin Lightning wallet and tic-tac-toe game XOXOBitcoin Lightning wallet and tic-tac-toe game XOXO
Bitcoin Lightning wallet and tic-tac-toe game XOXO
 
Acorn Recovery: Restore IT infra within minutes
Acorn Recovery: Restore IT infra within minutesAcorn Recovery: Restore IT infra within minutes
Acorn Recovery: Restore IT infra within minutes
 
Getting started with Amazon Bedrock Studio and Control Tower
Getting started with Amazon Bedrock Studio and Control TowerGetting started with Amazon Bedrock Studio and Control Tower
Getting started with Amazon Bedrock Studio and Control Tower
 
Obesity causes and management and associated medical conditions
Obesity causes and management and associated medical conditionsObesity causes and management and associated medical conditions
Obesity causes and management and associated medical conditions
 
Eureka, I found it! - Special Libraries Association 2021 Presentation
Eureka, I found it! - Special Libraries Association 2021 PresentationEureka, I found it! - Special Libraries Association 2021 Presentation
Eureka, I found it! - Special Libraries Association 2021 Presentation
 
Bonzo subscription_hjjjjjjjj5hhhhhhh_2024.pdf
Bonzo subscription_hjjjjjjjj5hhhhhhh_2024.pdfBonzo subscription_hjjjjjjjj5hhhhhhh_2024.pdf
Bonzo subscription_hjjjjjjjj5hhhhhhh_2024.pdf
 
International Workshop on Artificial Intelligence in Software Testing
International Workshop on Artificial Intelligence in Software TestingInternational Workshop on Artificial Intelligence in Software Testing
International Workshop on Artificial Intelligence in Software Testing
 
somanykidsbutsofewfathers-140705000023-phpapp02.pptx
somanykidsbutsofewfathers-140705000023-phpapp02.pptxsomanykidsbutsofewfathers-140705000023-phpapp02.pptx
somanykidsbutsofewfathers-140705000023-phpapp02.pptx
 
Doctoral Symposium at the 17th IEEE International Conference on Software Test...
Doctoral Symposium at the 17th IEEE International Conference on Software Test...Doctoral Symposium at the 17th IEEE International Conference on Software Test...
Doctoral Symposium at the 17th IEEE International Conference on Software Test...
 

Exploring billion states of a program like a pro. How to cook your own fast and scalable DBI-based security tool. A case study.

  • 1. © 2015 IBM Corporation How to cook your own fast and scalable DBI-based security tool. A case study Exploring billion states of a program like a pro 2017
  • 2. © 2015 IBM Corporation IBM Research - Haifa About me  PhD (Tomsk State University of Control Systems and Radioelectronics) – Vulnerabilities detection in machine code (x86)  Cyber Security Researcher at IBM Research Lab in Haifa, Israel – R&D in technologies for highly-evasive malware analysis and detection  A main contributor to DynamoRIO/DrMemory DBI frameworks 2017
  • 3. © 2015 IBM Corporation IBM Research - Haifa Outline  Dynamic binary instrumentation technique – General idea and technique implementation – DynamoRIO and Intel PIN frameworks comparison – Possible application fields  Example I. Heap-based bug detection using DBI – General idea & motivation – Implementation & issues – Solutions for described issues  Example II. Dynamic malware analysis – General idea & motivation – Implementation – Tool demo  Conclusion 2017
  • 4. © 2015 IBM Corporation IBM Research - Haifa Dynamic binary instrumentation (DBI) DBI is a technique of analyzing the behavior of a binary application at runtime through the injection of instrumentation code 2017
  • 5. © 2015 IBM Corporation IBM Research - Haifa How does it work ? Application launcher.exe core.dll DBI Engine CreateProcess (suspended) (1) Inject core.dll (2) Application in memory Windows kernel Takebasicblock (4)(3) Hook entry point core.dll + user dll/dlls shared system dlls ins1 ins2 ins3 insN . . Code cache basic block transformation (5) ins1 inst_ins1 inst_ins2 ins2 inst_ins3 inst_ins4 ins3 inst_ins4 inst_ins5 insN inst_insM inst_insM+1 Execute & calculate addr of next basic block (6) Takenextbasicblock (7) . .
  • 6. © 2015 IBM Corporation IBM Research - Haifa Frameworks Comparison DynamoRIO Intel PIN Redistribution model Open-source, BSD – license Proprietary, no-source code available Supported architectures x86, x86-64, ARM, AArch64 x86, x86-64 Supported Platforms Linux, Windows, MacOS, Android Linux, Windows, MacOS, Android Average runtime overhead 108% (no tool) 139% (BBs counter) 130% (no tool) 162% (BBs counter) Language C/C++ C/C++ (some Python wrappers available) Technology Binary code transformation callout/trampolines 2017
  • 7. © 2015 IBM Corporation IBM Research - Haifa Instructions Counting. Example DynamoRIOIntel PIN 2017
  • 8. © 2015 IBM Corporation IBM Research - Haifa Instrumentation Granularity Instruction level (instrument all executed instructions) Basic block level (instrument all executed basic blocks) Function call level (instrument all executed calls) Module level (instrument all load/unload module events) Events • exceptions/signals • syscalls • thread/process creation/deletion 2017
  • 9. © 2015 IBM Corporation IBM Research - Haifa Application  Software security analysis & testing – Support fuzzing (code coverage assessment, tainted input tracking) – Bugs detection (overflows, use-after-free, uninitialized access and etc.) – Symbolic execution – Software bugs exploitability assessment  Malware analysis – Execution tracing – Automatic unpacking  Reverse-engineering – Control-flow graph visualization – Debugging – Taint-tracking  Other non-security fields – Performance evaluation – Memory leak detection – Optimization 2017
  • 10. © 2015 IBM Corporation IBM Research - Haifa Example I. Bugs detection 2017
  • 11. © 2015 IBM Corporation IBM Research - Haifa WinHeap Explorer Tool  WinHeap Explorer is a system for heap-based bug detection with the lowest runtime overhead build on top of Intel PIN framework.  Advantages: – Light-weight instrumentation support (shown further) – Lowest runtime-overhead – Open-source (BSD license) 2017
  • 12. © 2015 IBM Corporation IBM Research - Haifa Motivation Example 2017
  • 13. © 2015 IBM Corporation IBM Research - Haifa Motivation Example 2017
  • 14. © 2015 IBM Corporation IBM Research - Haifa Motivation Example Heap memory block for a Heap Layout pMethod 1 pMethod 2 pMethod 3 pMethod 4 Virtual table for pFileOpen 2017
  • 15. © 2015 IBM Corporation IBM Research - Haifa Motivation Example Heap memory block for a pEvilMet 1 pMethod 2 pMethod 3 pMethod 4 Virtual table for pFileOpen Heap Layout 2017
  • 16. © 2015 IBM Corporation IBM Research - Haifa Detection of Heap-based Bugs. General Idea Code Heap instruction #1 instruction #2 instruction #3 instruction #4 instruction #5 0x0 – 0x3 0x4 – 0x7 0x8 – 0xB 0xC – 0xF 0x10 – 0x13 0x14 – 0x17 0x80 – 0x83 0x84 – 0x87 0x88 – 0x8B 0x8C – 0x8F 0x90 – 0x93 0x94 – 0x98 … 2017
  • 17. © 2015 IBM Corporation IBM Research - Haifa Detection of Heap-based Bugs. General Idea Code Heap instruction #1 instruction #2 instruction #3 instruction #4 instruction #5 0x0 – 0x3 0x4 – 0x7 0x8 – 0xB 0xC – 0xF 0x10 – 0x13 0x14 – 0x17 0x80 – 0x83 0x84 – 0x87 0x88 – 0x8B 0x8C – 0x8F 0x90 – 0x93 0x94 – 0x98 … Allocated memory block #1 Freed memory block #2 2017
  • 18. © 2015 IBM Corporation IBM Research - Haifa Detection of Heap-based Bugs. General Idea Code Correct instruction #1 Correct instruction #2 Incorrect instruction #3 Incorrect instruction #4 Incorrect instruction #5 [overflow] [access block #1] [access block #1] [underflow] [use after free] Heap 0x0 – 0x3 0x4 – 0x7 0x8 – 0xB 0xC – 0xF 0x10 – 0x13 0x14 – 0x17 0x80 – 0x83 0x84 – 0x87 0x88 – 0x8B 0x8C – 0x8F 0x90 – 0x93 0x94 – 0x98 … Allocated memory block #1 Freed memory block #2 2017
  • 19. © 2015 IBM Corporation IBM Research - Haifa Detection of Heap-based Bugs. General Idea Code Correct instruction #1 Correct instruction #2 Incorrect instruction #3 Incorrect instruction #4 Incorrect instruction #5 [overflow] [access block #1] [access block #1] [underflow] [use after free] Heap 0x0 – 0x3 0x4 – 0x7 0x8 – 0xB 0xC – 0xF 0x10 – 0x13 0x14 – 0x17 0x80 – 0x83 0x84 – 0x87 0x88 – 0x8B 0x8C – 0x8F 0x90 – 0x93 0x94 – 0x98 … Allocated memory block #1 Freed memory block #2 redzone redzone marked as freed 2017
  • 20. © 2015 IBM Corporation IBM Research - Haifa Detection of Heap-based Bugs. General Idea Code Correct instruction #1 Correct instruction #2 Incorrect instruction #3 Incorrect instruction #4 Incorrect instruction #5 [overflow] [access block #1] [access block #1] [underflow] [use after free] Heap 0x0 – 0x3 0x4 – 0x7 0x8 – 0xB 0xC – 0xF 0x10 – 0x13 0x14 – 0x17 0x80 – 0x83 0x84 – 0x87 0x88 – 0x8B 0x8C – 0x8F 0x90 – 0x93 0x94 – 0x98 … Allocated memory block #1 Freed memory block #2 redzone redzone marked as freed 𝑖𝑓 𝑝𝑜𝑖𝑛𝑡𝑒𝑟 ∈ 𝑟𝑒𝑑𝑧𝑜𝑛𝑒 𝑜𝑟 𝑝𝑜𝑖𝑛𝑡𝑒𝑟 ∈ 𝑓𝑟𝑒𝑒𝑑 𝑡ℎ𝑒𝑛 𝒃𝒖𝒈 2017
  • 21. © 2015 IBM Corporation IBM Research - Haifa Detection of Heap-based Bugs. General Idea Code Correct instruction #1 Correct instruction #2 Incorrect instruction #3 Incorrect instruction #4 Incorrect instruction #5 [overflow] [access block #1] [access block #1] [underflow] [use after free] Heap 0x0 – 0x3 0x4 – 0x7 0x8 – 0xB 0xC – 0xF 0x10 – 0x13 0x14 – 0x17 0x80 – 0x83 0x84 – 0x87 0x88 – 0x8B 0x8C – 0x8F 0x90 – 0x93 0x94 – 0x98 … Allocated memory block #1 Freed memory block #2 redzone redzone marked as freed 2017
  • 22. © 2015 IBM Corporation IBM Research - Haifa WinHeap Explorer. Implementation #1 Step 1. Instrument all heap management API calls (allocation/reallocation/freeing) Step 2. Save redzones and heap block statuses (freed or in use) in a hashtable Step 3. Instrument all executed instructions, dynamically check that an instruction doesn’t access redzone or previously freed memory block 2017
  • 23. © 2015 IBM Corporation IBM Research - Haifa WinHeap Explorer. Implementation #1 Step 1. Instrument all heap management API calls (allocation/reallocation/freeing) Step 2. Save redzones and heap block statuses (freed or in use) in a hashtable Step 3. Instrument all executed instructions, dynamically check that an instruction doesn’t access redzone or previously freed memory block. Results:  Runtime overhead: x310-x850 – Launching Mozilla Firefox = ~498M instructions (or 8 minutes to show first window) – Launching Acrobat Reader = ~84M instructions (or 3 minutes to show first window) – Launching PowerPoint = ~860M instructions (or 12 minutes to show first window)  Memory overhead: x90-x120 2017
  • 24. © 2015 IBM Corporation IBM Research - Haifa WinHeap Explorer. Implementation #1 Step 1. Instrument all heap management API calls (allocation/reallocation/freeing) Step 2. Save redzones and heap block statuses (freed or in use) in a hashtable Step 3. Instrument all executed instructions, dynamically check that an instruction doesn’t access redzone or previously freed memory block. Results:  Runtime overhead: x310-x850 – Launching Mozilla Firefox = ~498M instructions (or 8 minutes to show first window) – Launching Acrobat Reader = ~84M instructions (or 3 minutes to show first window) – Launching PowerPoint = ~860M instructions (or 12 minutes to show first window)  Memory overhead: x90-x120 Absolutely unacceptable 2017
  • 25. © 2015 IBM Corporation IBM Research - Haifa Shadow Memory Approach 2017
  • 26. © 2015 IBM Corporation IBM Research - Haifa Windows Heap Management APIs Architecture kernel32.dll HeapAlloc GlobalAlloc LocalAlloc Memory allocation msvcr*.dll malloc calloc new [] ole32.dll CoTaskMemAlloc kernel32.dll HeapReAlloc GlobalReAlloc LocalReAlloc Memory reallocation msvcr*.dll realloc ole32.dll CoTaskMemrealloc kernel32.dll HeapFree GlobalFree LocalFree Memory freeing msvcr*.dll free delete [] ole32.dll CoTaskMemFree ntdll.dll RtlAllocateHeap RtlReAllocateHeap RtlFreeHeap Windows Kernel 2017
  • 27. © 2015 IBM Corporation IBM Research - Haifa Light-weight instrumentation. System DLLs instrumentation 2017
  • 28. © 2015 IBM Corporation IBM Research - Haifa Light-weight instrumentation. Whole System Architecture 2017
  • 29. © 2015 IBM Corporation IBM Research - Haifa WinHeap Explorer. Runtime overhead #2 2017
  • 30. © 2015 IBM Corporation IBM Research - Haifa Example 2. Malware analysis 2017
  • 31. © 2015 IBM Corporation IBM Research - Haifa Dynamic Malware Analysis. Motivation 2017
  • 32. © 2015 IBM Corporation IBM Research - Haifa Dynamic Malware Analysis. Motivation 2017
  • 33. © 2015 IBM Corporation IBM Research - Haifa Dynamic Malware Analysis. Idea & Solution  Goal – transparently and efficiently trace malware’s library calls  Solution – Instrument calls to exported library functions – Print a trace of each executed function along with some arguments information – Print a return address of each executed function (to be able to recognize calls from unpacked code) 2017
  • 34. © 2015 IBM Corporation IBM Research - Haifa DrLtrace Tool  DrLtrace is a standalone application for transparent API calls tracing build on top of DynamoRIO framework.  Benefits: – Transparent (no API-hooking, no debugging) – High visibility (each API call, all arguments) – Open-source (BSD license) – Supported Windows, Linux, Android – Easy to use, just specify: drltrace.exe –logdir <log_name> -- <app_name> 2017
  • 35. © 2015 IBM Corporation IBM Research - Haifa Output Examples 2017
  • 36. © 2015 IBM Corporation IBM Research - Haifa DEMO 2017
  • 37. © 2015 IBM Corporation IBM Research - Haifa Conclusion  DBI is a powerful technique for transparent and efficient machine code introspection  Numerous possible ways to use, especially for software security analysis, dynamic malware introspection, reverse-engineering and etc.  Traditional fast and scalable data structures may introduce significant overhead in case of DBI  Two open-source tools were introduced: – WinHeap Explorer – a tool for heap-based bug detection in Windows applications – Dr.Ltrace – a tool for transparent dynamic library calls tracing 2017
  • 38. © 2015 IBM Corporation IBM Research - Haifa Links  WinHeapExplorer – https://github.com/WinHeapExplorer/WinHeap-Explorer  DrLtrace 1 - https://github.com/DynamoRIO/drmemory/tree/master/drltrace  Whitepaper - https://github.com/WinHeapExplorer/WinHeap-Explorer/tree/master/PHD 1 – please build from source code to have the latest functionality 2017
  • 39. © 2015 IBM Corporation IBM Research - Haifa Thank you for you attention! PhD, Research Staff Member (Cyber Security) IBM Research Israel Maksim Shudrak maksims@il.ibm.com mxmssh@gmail.com 2017

Editor's Notes

  1. Всем привет, меня зовут Максим Шудрак, я работаю cyber security researcherом в IBM Research Israel, мы занимаемся разработкой новых технологий для автоматизированного детектирования сложного вредоносного кода. Год назад я защитил диссертацию по поиску уязвимостей в исполняемом коде в Томском университете систем управления и радиоэлектроники. В свободное время я занимаюсь исследованием и разработкой утилит для анализа исполняемого кода, а также вношу вклад в разработку ДБИ фреймворка DynamoRIO.
  2. Мой доклад будет построен следующим обрзаом: в начале мы рассмотрим, что такое динамическая бинарная инструментация в общем, как она работает, приведем описание и сравнение двух наиболее популярных фреймворков, а также рассмотрим возможные области применения этой технологии. Затем я подробно расскажу о своем опыте работы с этой технологией на примере разработки двух утилит для автоматизированного детектирования ошибок типа переполнения кучи и динамического анализа вредоносного кода. Покажу DEMO одной утилиты и расскажу о некоторых подводных камнях при работе с DBI.
  3. Поехали. Динамическая бинарная инструментация или ДБИ это метод динамического анализа бинарных приложений путем внедрения инструментирующего кода. Звучит довольно просто, давайте посмотрим как это работает.
  4. Итак представим что у нас есть бинарник и наш ДБИ фреймворк, который состоит из лаунчера и основной dll. На первом этапе это выглядит как классический инжект длл в приложение. Мы запускаем наш бинарник в приостановленном состоянии, инжектируем базовую длл фреймворка, перепесываем точку входа, чтобы передать управление на нашу core.dll. Потом мы возобновляем процесс, он запускается и передает управление в core.dll. Core.dll в свою очередь подгружает все необходимые для его функционирования библиотеки, вычисляет адрес первого блока приложения которое должно выполниться. Затем мы берем этот базовый блок, копируем его в кодовый кэш, инжектируем инструкции или целые функции в соответствии с тем, как нам нужно выполнить инструментацию и выполняем этот блок в кеше, затем вычисляем следующий базовый блок, выполняем его инструментацию, исполняем и т.д., до тех пор пока вся программа не выполнится. Безусловно это обобщенная схема, на практике за этапом 5 стоит ряд сложнейших технологий.
  5. В моем докладе я бы хотел остановиться на двух самых популярных на сегодняшний день фреймворках DynamoRIO и Intel PIN. ДинамоРИО фреймворк поддерживаемый Google и ARM и Intel Pin поддерживаемый Intel. На мой взгляд DynamoRIO выгодно отличается от Intel PIN, он быстрее, распространяется под BSD-лицензией, поддерживает больше архитектур и гораздо более гибче с точки зрения используемой технологии. Однако Intel Pin гораздо проще с точки зрения разработки инструментирующий утилит и имеет больше примеров. Тоесть порог вхождение в него ниже.
  6. Код обоих фреймворков построен на вызове callback-процедур в зависимости от определенного события, например исполнения нового базового блока или функции.
  7. Инструментацию мы можем выполнять с разным уровнем так называемой гранулярности, мы можем инструментировать каждую инструкции, каждый базовый блок, каждый вызов функции или срабатывание определенного события, например загрузки модуля, исключения или системного вызова.
  8. На сегодняшний день, ДБИ применяется в огромном количестве направлений, это поиск уязвимостей, тестирование и верификация программного обеспечения, обнаружение НДВ, динамический анализ вредоносного кода, реверс-инжиниринг, а также во многих других направлениях связанных с анализом качества программного обеспечения.
  9. Рассмотрим один из вариантов применения ДБИ на примере поиска ошибок типа переполнения кучи в исполняемом коде.
  10. В рамках работы с фреймворком Intel Pin, мною была разработана утилита WinHeap Explorer, которая как раз позволяет выполнять детектирование таких ошибок. Основными преимуществами этой утилиты по сравнению с аналогами является возможность выполнять частичную инструментацию ( я расскажу о ней далее), низкие накладные расходы, а также открытый исходный код под BSD - лицензией.
  11. Я думаю присутствующим не нужно рассказывать об опасности ошибок типа переполнения кучи, однако на всякий случай я приведу пример. Представим что у нас есть вот такой вот код. У нас выделяется память с помощью malloc, затем выполняеться вызов CoCreateInstance с целью создать интерфейс для FileOpenDialog
  12. , а затем на строчке 12 у нас есть переполнение буфера.
  13. Такая ошибка чревата тем, что если 2 наших блока памяти выделяться один за другим, то есть существует достаточно приличная вероятность такого события. В таком случае у нас будет возможность выполнить так называемый vtable corruption или перезаписать таблицу виртуальных методов (vtable for pFileOpen на слайде).
  14. Перезаписываем указатель на метод в pFileOpen, это позволит нам выполнить произвольный код в контексте уязвимого приложения. Конечно еще нужно, чтобы этот метод вызвался, но это уже не слишком сложно. Как вы видите у нас есть здесь выход за границы выделенной кучи. Что если мы бы могли каким-либо образом запоминать размер выделенной кучи и сигнализировать в том случае, если программа выполняет запись за его пределами. Вот здесь нам может очень помочь DBI.
  15. Итак представим что у нас есть 5 инструкций и 2 выделенных блока в куче.
  16. Один блок доступный для чтения/записи, а второй уже освободился.
  17. Представим что 2 наши инструкции корректно обращаются к памяти. А 2 другие пишут за границами выделенной памяти, а последняя обращается к уже освобожденному блоку памяти. Классический buffer overflow и use-after-free.
  18. Что детектировать эти ошибки, пометим память до и после выделенного блока как redzone, а уже освобжденному блоку памяти присвоим специальный маркер.
  19. Теперь если инструкция осуществляет доступ к redzone или к блоку помеченному как освобожденный, мы считаем такую ситуацию как ошибка.
  20. И тем самым детектируем где у нас происходит оверфлоу или use-after-free. Звучит довольно просто, перейдем к реализации с помощью DBI.
  21. Для того чтобы пометить каждый выделыемый блок памяти, нам нужно инструментировать API вызовы освобождения или выделения памяти, а также анализировать указатели каждой инструкции. Редзоны и статус каждого выделенного блока памяти будем хранить в куче. Все логично, и это будет работать. Но есть одна проблема.
  22. Производительность просто ужасная, запуск повер-поинта длиться 12 минут
  23. Это абсолютно неприемлимо, мы не сможем привязать фаззер или интегрировать нашу утилиту в процесс разработки. Окей, что мы можем сделать чтобы исправить эту ситуацию.
  24. Во первых хранить все в хештейбл для нас слишком затратно. Заместо будем использовать теневую память. Куча выделяется с выравниванием в 8 байт, таким образом мы можем очень легко отразить, каждые восемь байт выделяемые в куче, на 1 байт в теневой памяти, используя простейшую арифметику, беря остаток от деления адреса на 8 и прибавляя его к базовому адресу по которому выделена теневая память. В этом же байте теневой памяти будем хранить и статус выделенного блока – доступен, освобожден или redzone.
  25. Отлично далее. Я проанилизировал архитектуру выделения памяти в Windows и пришел к выводу, что нам не нужно инструментировать все функции, достаточно лишь инструменитровать Rtl вызовы в ntdll.dll. Все высокоуровневые функции, так или иначе будут использовать их для выделения памяти. Ну а они уже в свою очередь системный вызов в ядро.
  26. Далее. Что можно сделать еще. Если мы проанализируем соотношение количества выполняемых инструкций в приложении и DLL, мы можем прийти к выводу, что очень много времени проводится в системных DLL, хотя нам их не нужно тестировать. На слайде приведено отношение, процент показывает соотношение количества выполненных инструкций в системных DLL к пользовательским. К сожалению мы не можем просто не инструментировать код системных библиотек, однако мы можем добавить только те функции, которые действительно интересны с точки зрения анализа, например функции обработки строк, памяти и т.п.
  27. Для этого я реализовал несколько скриптов на Pythonе, которые используют IDA, и которые позволяют составить список таких функций для WinHeap Explorer еще до начала анализа. Они сохраняются в базу, а затем в ходе тестирования WinHeap Explorer используют их для принятие решения об инструментации того или иного участка кода.
  28. В результате удалось повысить производительность примерно в 70 раз и обогнать state-of-the-art утилиту в этой области DrMemory, разрабатываемую Google, в некоторых случаях на 70%.
  29. Перейдем к следующему примеру. Анализ вредоносного кода.
  30. Здесь я бы хотел показать пример применения технологии ДБИ для динамического анализа вредоносного кода. Итак предположим у нас есть вирус, хорошо упакованный, обфусцированный и в котором есть механизмы защиты от отладки и API-хукинга. Мы не хотим заниматься ручным реверсингом этого семпла, но нам необходимо понять, что он делает. Традиционным подходом в таком случае будет использование различных утилит мониторинга операционной системы, например RegMon и SysMon, Wireshark для сети и т.д. Однако в такой ситуации мы сталкиваемся с так называемой проблемой называемой в Computer Science: Semantic Gap. Мы видим взаимодействие нашего семлпа с ОС, однако его внутренние механизмы попрежнему остаются для нас черным ящиком.
  31. Хорошо, в таком случае мы можем использовать API-hooking и видеть каждый API - вызов, однако это очень известная техника, которая очень легко детектируется да и производительность и стабильность такого подхода вызывает вопросы.
  32. Вот как раз для решения этой проблемы отличны подходит ДБИ. Мы можем выполнить инструментацию каждой экспортируемой функцией из подгружаемых семплом библиотек и печатать информацию в лог, каждый раз когда к ней происходит вызов.
  33. Этот подход был реализован мною в утилите DrlTrace, построенной на базе DynamoRIO. Почему DynamoRIO, потому что основным принципом при разработке DynamoRIO являлась прозрачность по отношению к исполняемому коду. Это позволяет снизить потенциальный риск обнаружения утилиты малварью. Утилита доступна онлайн, лицензия BSD, работает в Windows,, Linux и под Android. Использовать её очень просто, достаточно одной команды, которая приведена на слайде.
  34. Вот такой лог она будет генерировать в файл. Давайте посмотрим его на реальном примере.
  35. Итак подведем итог. ДБИ это очень мощная технология, которая может использоваться во многих сфера информационной безопасности и если применять её правильно и использовать ряд оптимизаций рассмотренных в презентации, можно добиться отличных результатов, что и было продемонстрировано на примере двух утилит WinHeap Explorer и Dr.Ltrace.
  36. Их можно скачать на github, спасибо за внимание, готовь ответить на вопросы.