SlideShare a Scribd company logo
1
Hijacking Arbitrary .NET Application Control
Flow
Topher Timzen
&
Ryan Allen
Southern Oregon University Cybersecurity Research Lab
F
ABSTRACT
This paper describes the use of Reflection in
.NET and how it can be utilized to change
the control flow of an arbitrary application at
runtime. A tool, Gray Storm, will be introduced
that can be injected into an AppDomain and
used to control the executing assembly instruc-
tions after just-in-time compilation.
1 INTRODUCTION
The .NET Framework is used in a variety of
enterprise applications such as fingerprint read-
ers and SQL databases with the C# program-
ming language. Through the use of Reflection
the framework grants the ability to look at
metadata for assemblies, classes, and methods
within an application. This ability allows a ma-
licious application to read the metadata of a
specific entity in a running AppDomain. That
information can be utilized to modify the be-
havior of a target process’s AppDomain at run-
time.
.NET AppDomains are equivalent to a pro-
cess and are containers for running code. An
application may have several AppDomains and
all of them can be accessed through Reflection.
Because of the nature of just-in-time compila-
tion (JIT/Jitter), memory is marked readable,
writable and executable (rwx) as the JIT com-
piler needs to write generated machine code
from Intermediate Language (IL) to memory for
execution.
Gray Storm takes advantage of the way the
.NET Framework uses Reflection and JIT. It
allows an attacker to read, write and change
existing methods. This can be done with com-
piled on-the-fly C# code or arbitrary assembly
payloads.
2 .NET BASICS
When an application is compiled, IL code is
generated through implicit compilation [5]. The
.NET Framework will then generate machine
code at runtime. The common language run-
time (CLR) is used by the framework to gen-
erate assembly code from IL code. IL code is
an independent set of instructions that are con-
verted to native machine code at JIT [6]. When a
method is about to be executed, the framework
uses JIT to generate assembly code that the CPU
can execute by accessing a JIT stub. IL is fairly
human readable and shows which methods a
given method calls. Utilizing IL, individuals are
able to trace the control flow of an application
easily.
2
2.1 JIT
The CLR reads the metadata from the IL and
allocates memory for the machine code. This
memory is readable, writable and executable
as the JIT needs to be able to write code to
memory and have it execute. The following is
output from WinDbg showing rwx memory on
a method that has been just-in-time compiled.
0:008> ! address 1EB4F8
Usage : <unknown>
Base Address : 00000000 ‘001 e0000
End Address : 00000000 ‘001 ed000
Region Size : 00000000 ‘0000 d000
State : 00001000 MEM COMMIT
Protect 00000040 PAGE EXECUTE READWRITE
Type : 00020000 MEM PRIVATE
Allocation Base : 00000000 ‘001 e0000
Allocation Protect : 00000001 PAGE NOACCESS
The JIT compiler leaves memory rwx af-
ter it writes executable code to memory. That
memory can then be overwritten with arbitrary
assembly instructions.
2.2 Reflection
A .NET Assembly is a definition of types, man-
ifests and other metadata constructs [4]. As-
semblies contain specific classes, whether they
be libraries or programmer generated, and the
methods within them. Reflection provides a
library of classes in the .NET Framework that
give the ability to look at the metadata of As-
semblies. With Reflection the programmer can
look at the return type and arguments of a
method and the address of a method’s gener-
ated assembly. Furthermore, Reflection shows
all AppDomains within a process and all of the
constructors within a class.
Gray Storm utilizes the ability of Reflec-
tion to see the function pointer of the rwx
memory the JIT produces. Reflection contains
a MethodInfo class that has the attributes of a
method. MethodInfo contains a MethodHandle
that gets an internal metadata representation
of a method. With that, a call to GetFunction-
Pointer() gives the address of the rwx memory
where the JIT compiler will place the assembly
code.
IntPtr funPtr = ( IntPtr ) MethodInfo .
MethodHandle . GetFunctionPointer ( ) .
ToInt64 ( ) ;
Reflection also allows the user to see all the
binding flags used on a method such as static,
public and private. This information can be
used to generate code at runtime and overwrite
the assembly in a target method with malicious
code.
3 GRAY STORM
Using the capabilities of Reflection in conjunc-
tion with rwx memory, Gray Storm takes ad-
vantage of the .NET Framework to operate
maliciously in an AppDomain. Several attack
chains have been implemented within a pro-
cess. They are able to adjust arbitrary call se-
quences to alter control flow, overwrite Method
Tables and compile new C# classes on-the-
fly. Furthermore the tool allows an attacker
to change existing Method Table pointers to
point to new methods, as well as granting the
ability to replace original assembly with custom
assembly payloads.
DigitalBodyGuard described an injection
platform and Gray Storm utilizes the same
methods to inject itself into a target [3]. The
tool is packaged into a byte array and shipped
with a C++ DLL, Gray Frost, that acts as a boot-
strapper, which targets the main AppDomain in
a .NET application. This bootstrapper process
also determines the .NET runtime that a specific
application is using and pivots from 4.0 to 2.0
if necessary. As of now remote DLL injection is
used but there is work underway to implement
a Metasploit module and utilize reflective DLL
injection. By using the bootstrapper approach,
Gray Storm is injectable into any arbitrary .NET
application.
3.1 Method Calls
While looking at the assembly code that the Jit-
ter places into rwx memory, the authors noticed
two different calling conventions used in x86.
The Jitter appears to output both relative and
far calls
0xE8/Call [imm]
0xFF 0x15/Call dword [imm]
By looking at the IL code before the JIT, it
can be accurately determined which calls call
3
which methods. Calls can then be changed to
an address under attacker control. For exam-
ple, the following IL code generates the 0xE8
relative call.
MSIL : 0008 c a l l System . Void memoryHijacker .
abc . t e s t C a l l ( System . Int32 )
ASM: 0xE8 c a l l 730ECAD9h
The far call instruction is 6 bytes, 0xFF 0x15
0x## 0x## 0x## 0x##, and a relative call is 5
bytes, lengthOfCall below, 0xE8 0x## 0x## 0x##
0x##. An attacker can thus change a far call into
a relative call by using the algorithm described
in the IA32 manual [2] and a NOP instruction
on the 6th byte on the far call to change the
instruction to a relative one.
relativeCallAddress = dstAddress
( currentLocation + indexInMemoryToCall
+ lengthOfCall )
Changing a relative call is fairly easy as you
just overwrite the 4 bytes of the immediate with
the new destination address. Gray Storm has
the ability to use an arbitrary address in a call
instruction thanks to Reflection.
3.2 Method Table
Ziad Elmalki described a way to replace
Method Tables at runtime because Method Ta-
bles have the addresses of the JIT stubs for a
class’s methods [1]. He goes on to show that if
a method has not gone through JIT it references
the Method Table to generate addresses for
method calls. Elmalki showed that the Method
Table can be located in memory using Reflec-
tion and then changed so when referenced dur-
ing JIT, the address of the call instruction can be
altered
Gray Storm utilizes this capability and al-
lows any method to be the new target in a
Method Table. On-the-fly C# methods or pre-
existing ones can be used to change the control
flow before a method is JIT compiled. The pro-
totype to perform this change is listed below.
All that is needed is two MethodInfo types
so their Method Tables can be viewed with
Reflection.
public s t a t i c void ReplaceMethod ( MethodInfo
replacerMethod , MethodInfo targetMethod )
The above method will go through and
find the MethodHandle of both methods and
change the address of the targetMethods table
to point to our replacerMethod.
Unfortunately, this technique requires that a
method has not yet been JIT compiled. It is not
yet known how to force the garbage collector
to clean up a method so the table is referenced
again. This technique does however provide a
way to maintain persistence after garbage col-
lection as Gray Storm can change a call address
as shown in section 3.1 for the duration of an
object.
The .NET Framework provides CSharp-
CodeProvider [7] to compile code at runtime.
A user can input C# namespaces, classes and
methods and run them as if they were compiled
with the actual program. Using CSharpCode-
Provider, Gray Storm can perform the afore-
mentioned techniques to utilize newly created
run-time methods.
Once a method is compiled, it can be
invoked or used as a replacer to overwrite
Method Table pointers. An attacker can compile
any methods they want and if the exact return
type and arguments of an original programmed
method are matched, can execute a replacement
method without crashing the injected applica-
tion. This feature of the framework grants the
ability to read IL and assembly code, rewrite
a method in memory and then use it. For ex-
ample, the authors have written methods in
memory that send an encrypted e-mail of a
users password as they login by changing the
control flow of an application.
4
3.3 Assembly Level
Again because memory written by the JIT com-
piler is rwx, Gray Storm is able to write over
it with arbitrary assembly instructions. Custom
assembly payloads or MetaSploit payloads can
be used and placed over existing methods.
Performing this action is as simple as finding
the address of a method’s executable memory
from Reflection and writing over it with new
assembly code. If a payload is longer than the
space the current method takes in memory,
a user can restructure their assembly code to
support a form of hooking.
This hooking mechanism allows an attacker
to supply an arbitrarily long payload while also
allowing an attacker to restore the method as
if no code had been changed. The hooking is
achieved by creating a 7 byte sequence of the
following assembly.
0xB8 0x## 0x## 0x## 0x## //mov eax memory
0xFF 0xD0 // c a l l eax
The value of a payload is placed into the
memory address that is moved into EAX and
then called. In order to restore the original
method, the payload needs to be constructed to
make room for a payload cleaner that consumes
12 bytes before the payload returns. By creating
a cleaner stub with the original return method
value the original memory and EIP can be re-
stored to the method prelude. This ensures that
once a payload runs, it can restore the method
as if no changes were made to control flow.
Gray Storm includes a shell code editor
that allows a user to import arbitrary assembly
code. Furthermore, it provides the ability to
restore a method’s original code should the
attacker want to undo their actions.
3.4 Object Manipulation
Within Gray Storm tool there is an attack chain
to find and use instantiated objects at runtime.
A classes constructor can be discovered using
Reflection and a new one can be instantiated
locally. Once an arbitrary object is constructed
the attack chain finds the location of the man-
aged heap, signatures the instantiated object,
scans the managed heap and then converts the
managed heap object pointers into raw objects
[8]. Once objects are referenced locally all of
their fields, properties and instance methods
can be seen and utilized.
4 CONCLUSION
The .NET Framework allows for an attacker to
inject into an AppDomain and reflectively learn
about the workings of an application. Because
Microsoft chose to leave memory readable,
writable and executable after a JIT compilation,
an attacker is able to control the executing
assembly, change control flow and overwrite
Method Tables. Through Gray Storm it has
been demonstrated that the .NET Framework is
insecure by design and an arbitrary application
can be changed at an attackers whim.
5 FUTURE WORK
There are still improvements that can be made
to the aforementioned attack chains. As de-
scribed in 3.4, Gray Storm has the ability to
hook a method for a one time use. Adding the
ability to restore our payload without attacker
interaction would be useful and will be imple-
mented soon. Furthermore, the proof of concept
for this tool was written in x86 assembly and
work is currently underway to have full com-
patibility with x64.
6 ACKNOWLEDGMENTS
The authors would like to thank Jon of Digi-
talBodyGuard for assisting in researching .NET
attack vectors and teaching them the power of
using Reflection for attacking. Through his help
they were able to inject Gray Storm successfully
into arbitrary .NET applications. Furthermore,
Dr. Lynn Ackler, assistant professor at SOU,
for constantly being an encouragement and
providing the cybersecurity research lab to all
computer science students at the university.
5
REFERENCES
[1] Elmalki, Ziad. CLR Injection. Jun 2009.
http://www.codeproject.com/Articles/37549/CLR-
Injection-Runtime-Method-Replacer
[2] Intel 64 and IA-32 Architectures Software Developers Manual.
Number 325383-053US. January 2015.
[3] Jon. Hacking .Net Application at Runtime. In OWASP
APPSEC DC, Nov. 2010.
[4] Jon. Reflections Hidden Power. May 2002.
[5] Microsoft Corporation. .NET Framework 3.5. Compiling to
MSIL.
[6] Microsoft Corporation. .NET Framework 3.5. Compiling
MSIL to Native Code.
[7] Ponnupandy, Mercy. Dynamic Code Gen-
eration and Code Compilation. Dec 2002.
http://www.codeproject.com/Articles/3289/Dynamic-
Code-Generation-and-Code-Compilation
[8] Timzen, Topher. Acquiring .NET Objects from the Managed
Heap. May 2015.

More Related Content

PDF
PDF
C and CPP Interview Questions
PDF
C programming session6
PDF
C programming session10
PDF
Introduction to C Language - Version 1.0 by Mark John Lado
PDF
C programming first_session
PDF
Handout#12
PDF
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
C and CPP Interview Questions
C programming session6
C programming session10
Introduction to C Language - Version 1.0 by Mark John Lado
C programming first_session
Handout#12
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE

What's hot (18)

PPTX
C programming interview questions
PDF
Handout#01
PDF
150104 3 methods for-binary_analysis_and_valgrind
PDF
De-virtualizing virtual Function Calls using various Type Analysis Technique...
PDF
Porting is a Delicate Matter: Checking Far Manager under Linux
PDF
88 c-programs
PPTX
Compiler
PDF
First session quiz
PPTX
POLITEKNIK MALAYSIA
PPT
C++ Interview Questions
DOCX
Dineshmaterial1 091225091539-phpapp02
PPTX
Macro Processor
PDF
ANSI C Macros
PDF
Binary code obfuscation through c++ template meta programming
PDF
Java chapter 5
PPTX
Unit 4 sp macro
PDF
Python for Machine Learning
PPTX
How c/c++ works
C programming interview questions
Handout#01
150104 3 methods for-binary_analysis_and_valgrind
De-virtualizing virtual Function Calls using various Type Analysis Technique...
Porting is a Delicate Matter: Checking Far Manager under Linux
88 c-programs
Compiler
First session quiz
POLITEKNIK MALAYSIA
C++ Interview Questions
Dineshmaterial1 091225091539-phpapp02
Macro Processor
ANSI C Macros
Binary code obfuscation through c++ template meta programming
Java chapter 5
Unit 4 sp macro
Python for Machine Learning
How c/c++ works
Ad

Similar to DEF CON 23 - Topher Timzen and Ryan Allen - Hijacking Arbitrary NET App Control Flow (20)

PDF
Dot NET Interview Questions PDF By ScholarHat
PDF
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
PDF
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
PPTX
GCC RTL and Machine Description
PPT
Distributed System by Pratik Tambekar
PDF
16-bit Microprocessor Design (2005)
PDF
Directive-based approach to Heterogeneous Computing
PDF
SP_Solutions_-Adi.pdf
PDF
SP Solutions -Adi.pdf
PDF
SP_Solutions_-Adi.pdf
PPTX
Intermediate Representation in Compiler Construction
DOCX
C# Unit 1 notes
DOC
Chapter 6
PPTX
06 chapter03 04_control_logix_tags_memory_structure_fa16
PDF
Aspect Oriented Programming Through C#.NET
DOCX
Net Interview questions
PPT
C sharp
PDF
C# c# for beginners crash course master c# programming fast and easy today
PPTX
Systems analysis and design in a changing world 5E.pptx
PDF
Chap 2_ans.pdf
Dot NET Interview Questions PDF By ScholarHat
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
GCC RTL and Machine Description
Distributed System by Pratik Tambekar
16-bit Microprocessor Design (2005)
Directive-based approach to Heterogeneous Computing
SP_Solutions_-Adi.pdf
SP Solutions -Adi.pdf
SP_Solutions_-Adi.pdf
Intermediate Representation in Compiler Construction
C# Unit 1 notes
Chapter 6
06 chapter03 04_control_logix_tags_memory_structure_fa16
Aspect Oriented Programming Through C#.NET
Net Interview questions
C sharp
C# c# for beginners crash course master c# programming fast and easy today
Systems analysis and design in a changing world 5E.pptx
Chap 2_ans.pdf
Ad

More from Felipe Prado (20)

PDF
DEF CON 24 - Sean Metcalf - beyond the mcse red teaming active directory
PDF
DEF CON 24 - Bertin Bervis and James Jara - exploiting and attacking seismolo...
PDF
DEF CON 24 - Tamas Szakaly - help i got ants
PDF
DEF CON 24 - Ladar Levison - compelled decryption
PDF
DEF CON 24 - Clarence Chio - machine duping 101
PDF
DEF CON 24 - Chris Rock - how to overthrow a government
PDF
DEF CON 24 - Fitzpatrick and Grand - 101 ways to brick your hardware
PDF
DEF CON 24 - Rogan Dawes and Dominic White - universal serial aBUSe remote at...
PDF
DEF CON 24 - Jay Beale and Larry Pesce - phishing without frustration
PDF
DEF CON 24 - Gorenc Sands - hacker machine interface
PDF
DEF CON 24 - Allan Cecil and DwangoAC - tasbot the perfectionist
PDF
DEF CON 24 - Rose and Ramsey - picking bluetooth low energy locks
PDF
DEF CON 24 - Rich Mogull - pragmatic cloud security
PDF
DEF CON 24 - Grant Bugher - Bypassing captive portals
PDF
DEF CON 24 - Patrick Wardle - 99 problems little snitch
PDF
DEF CON 24 - Plore - side -channel attacks on high security electronic safe l...
PDF
DEF CON 24 - Six Volts and Haystack - cheap tools for hacking heavy trucks
PDF
DEF CON 24 - Dinesh and Shetty - practical android application exploitation
PDF
DEF CON 24 - Klijnsma and Tentler - stargate pivoting through vnc
PDF
DEF CON 24 - Antonio Joseph - fuzzing android devices
DEF CON 24 - Sean Metcalf - beyond the mcse red teaming active directory
DEF CON 24 - Bertin Bervis and James Jara - exploiting and attacking seismolo...
DEF CON 24 - Tamas Szakaly - help i got ants
DEF CON 24 - Ladar Levison - compelled decryption
DEF CON 24 - Clarence Chio - machine duping 101
DEF CON 24 - Chris Rock - how to overthrow a government
DEF CON 24 - Fitzpatrick and Grand - 101 ways to brick your hardware
DEF CON 24 - Rogan Dawes and Dominic White - universal serial aBUSe remote at...
DEF CON 24 - Jay Beale and Larry Pesce - phishing without frustration
DEF CON 24 - Gorenc Sands - hacker machine interface
DEF CON 24 - Allan Cecil and DwangoAC - tasbot the perfectionist
DEF CON 24 - Rose and Ramsey - picking bluetooth low energy locks
DEF CON 24 - Rich Mogull - pragmatic cloud security
DEF CON 24 - Grant Bugher - Bypassing captive portals
DEF CON 24 - Patrick Wardle - 99 problems little snitch
DEF CON 24 - Plore - side -channel attacks on high security electronic safe l...
DEF CON 24 - Six Volts and Haystack - cheap tools for hacking heavy trucks
DEF CON 24 - Dinesh and Shetty - practical android application exploitation
DEF CON 24 - Klijnsma and Tentler - stargate pivoting through vnc
DEF CON 24 - Antonio Joseph - fuzzing android devices

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Getting Started with Data Integration: FME Form 101
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Encapsulation theory and applications.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Tartificialntelligence_presentation.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
cuic standard and advanced reporting.pdf
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
1. Introduction to Computer Programming.pptx
PPTX
A Presentation on Artificial Intelligence
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
Unlocking AI with Model Context Protocol (MCP)
Diabetes mellitus diagnosis method based random forest with bat algorithm
Getting Started with Data Integration: FME Form 101
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Machine learning based COVID-19 study performance prediction
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Mobile App Security Testing_ A Comprehensive Guide.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Encapsulation theory and applications.pdf
Programs and apps: productivity, graphics, security and other tools
Network Security Unit 5.pdf for BCA BBA.
Tartificialntelligence_presentation.pptx
Empathic Computing: Creating Shared Understanding
cuic standard and advanced reporting.pdf
SOPHOS-XG Firewall Administrator PPT.pptx
1. Introduction to Computer Programming.pptx
A Presentation on Artificial Intelligence
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing

DEF CON 23 - Topher Timzen and Ryan Allen - Hijacking Arbitrary NET App Control Flow

  • 1. 1 Hijacking Arbitrary .NET Application Control Flow Topher Timzen & Ryan Allen Southern Oregon University Cybersecurity Research Lab F ABSTRACT This paper describes the use of Reflection in .NET and how it can be utilized to change the control flow of an arbitrary application at runtime. A tool, Gray Storm, will be introduced that can be injected into an AppDomain and used to control the executing assembly instruc- tions after just-in-time compilation. 1 INTRODUCTION The .NET Framework is used in a variety of enterprise applications such as fingerprint read- ers and SQL databases with the C# program- ming language. Through the use of Reflection the framework grants the ability to look at metadata for assemblies, classes, and methods within an application. This ability allows a ma- licious application to read the metadata of a specific entity in a running AppDomain. That information can be utilized to modify the be- havior of a target process’s AppDomain at run- time. .NET AppDomains are equivalent to a pro- cess and are containers for running code. An application may have several AppDomains and all of them can be accessed through Reflection. Because of the nature of just-in-time compila- tion (JIT/Jitter), memory is marked readable, writable and executable (rwx) as the JIT com- piler needs to write generated machine code from Intermediate Language (IL) to memory for execution. Gray Storm takes advantage of the way the .NET Framework uses Reflection and JIT. It allows an attacker to read, write and change existing methods. This can be done with com- piled on-the-fly C# code or arbitrary assembly payloads. 2 .NET BASICS When an application is compiled, IL code is generated through implicit compilation [5]. The .NET Framework will then generate machine code at runtime. The common language run- time (CLR) is used by the framework to gen- erate assembly code from IL code. IL code is an independent set of instructions that are con- verted to native machine code at JIT [6]. When a method is about to be executed, the framework uses JIT to generate assembly code that the CPU can execute by accessing a JIT stub. IL is fairly human readable and shows which methods a given method calls. Utilizing IL, individuals are able to trace the control flow of an application easily.
  • 2. 2 2.1 JIT The CLR reads the metadata from the IL and allocates memory for the machine code. This memory is readable, writable and executable as the JIT needs to be able to write code to memory and have it execute. The following is output from WinDbg showing rwx memory on a method that has been just-in-time compiled. 0:008> ! address 1EB4F8 Usage : <unknown> Base Address : 00000000 ‘001 e0000 End Address : 00000000 ‘001 ed000 Region Size : 00000000 ‘0000 d000 State : 00001000 MEM COMMIT Protect 00000040 PAGE EXECUTE READWRITE Type : 00020000 MEM PRIVATE Allocation Base : 00000000 ‘001 e0000 Allocation Protect : 00000001 PAGE NOACCESS The JIT compiler leaves memory rwx af- ter it writes executable code to memory. That memory can then be overwritten with arbitrary assembly instructions. 2.2 Reflection A .NET Assembly is a definition of types, man- ifests and other metadata constructs [4]. As- semblies contain specific classes, whether they be libraries or programmer generated, and the methods within them. Reflection provides a library of classes in the .NET Framework that give the ability to look at the metadata of As- semblies. With Reflection the programmer can look at the return type and arguments of a method and the address of a method’s gener- ated assembly. Furthermore, Reflection shows all AppDomains within a process and all of the constructors within a class. Gray Storm utilizes the ability of Reflec- tion to see the function pointer of the rwx memory the JIT produces. Reflection contains a MethodInfo class that has the attributes of a method. MethodInfo contains a MethodHandle that gets an internal metadata representation of a method. With that, a call to GetFunction- Pointer() gives the address of the rwx memory where the JIT compiler will place the assembly code. IntPtr funPtr = ( IntPtr ) MethodInfo . MethodHandle . GetFunctionPointer ( ) . ToInt64 ( ) ; Reflection also allows the user to see all the binding flags used on a method such as static, public and private. This information can be used to generate code at runtime and overwrite the assembly in a target method with malicious code. 3 GRAY STORM Using the capabilities of Reflection in conjunc- tion with rwx memory, Gray Storm takes ad- vantage of the .NET Framework to operate maliciously in an AppDomain. Several attack chains have been implemented within a pro- cess. They are able to adjust arbitrary call se- quences to alter control flow, overwrite Method Tables and compile new C# classes on-the- fly. Furthermore the tool allows an attacker to change existing Method Table pointers to point to new methods, as well as granting the ability to replace original assembly with custom assembly payloads. DigitalBodyGuard described an injection platform and Gray Storm utilizes the same methods to inject itself into a target [3]. The tool is packaged into a byte array and shipped with a C++ DLL, Gray Frost, that acts as a boot- strapper, which targets the main AppDomain in a .NET application. This bootstrapper process also determines the .NET runtime that a specific application is using and pivots from 4.0 to 2.0 if necessary. As of now remote DLL injection is used but there is work underway to implement a Metasploit module and utilize reflective DLL injection. By using the bootstrapper approach, Gray Storm is injectable into any arbitrary .NET application. 3.1 Method Calls While looking at the assembly code that the Jit- ter places into rwx memory, the authors noticed two different calling conventions used in x86. The Jitter appears to output both relative and far calls 0xE8/Call [imm] 0xFF 0x15/Call dword [imm] By looking at the IL code before the JIT, it can be accurately determined which calls call
  • 3. 3 which methods. Calls can then be changed to an address under attacker control. For exam- ple, the following IL code generates the 0xE8 relative call. MSIL : 0008 c a l l System . Void memoryHijacker . abc . t e s t C a l l ( System . Int32 ) ASM: 0xE8 c a l l 730ECAD9h The far call instruction is 6 bytes, 0xFF 0x15 0x## 0x## 0x## 0x##, and a relative call is 5 bytes, lengthOfCall below, 0xE8 0x## 0x## 0x## 0x##. An attacker can thus change a far call into a relative call by using the algorithm described in the IA32 manual [2] and a NOP instruction on the 6th byte on the far call to change the instruction to a relative one. relativeCallAddress = dstAddress ( currentLocation + indexInMemoryToCall + lengthOfCall ) Changing a relative call is fairly easy as you just overwrite the 4 bytes of the immediate with the new destination address. Gray Storm has the ability to use an arbitrary address in a call instruction thanks to Reflection. 3.2 Method Table Ziad Elmalki described a way to replace Method Tables at runtime because Method Ta- bles have the addresses of the JIT stubs for a class’s methods [1]. He goes on to show that if a method has not gone through JIT it references the Method Table to generate addresses for method calls. Elmalki showed that the Method Table can be located in memory using Reflec- tion and then changed so when referenced dur- ing JIT, the address of the call instruction can be altered Gray Storm utilizes this capability and al- lows any method to be the new target in a Method Table. On-the-fly C# methods or pre- existing ones can be used to change the control flow before a method is JIT compiled. The pro- totype to perform this change is listed below. All that is needed is two MethodInfo types so their Method Tables can be viewed with Reflection. public s t a t i c void ReplaceMethod ( MethodInfo replacerMethod , MethodInfo targetMethod ) The above method will go through and find the MethodHandle of both methods and change the address of the targetMethods table to point to our replacerMethod. Unfortunately, this technique requires that a method has not yet been JIT compiled. It is not yet known how to force the garbage collector to clean up a method so the table is referenced again. This technique does however provide a way to maintain persistence after garbage col- lection as Gray Storm can change a call address as shown in section 3.1 for the duration of an object. The .NET Framework provides CSharp- CodeProvider [7] to compile code at runtime. A user can input C# namespaces, classes and methods and run them as if they were compiled with the actual program. Using CSharpCode- Provider, Gray Storm can perform the afore- mentioned techniques to utilize newly created run-time methods. Once a method is compiled, it can be invoked or used as a replacer to overwrite Method Table pointers. An attacker can compile any methods they want and if the exact return type and arguments of an original programmed method are matched, can execute a replacement method without crashing the injected applica- tion. This feature of the framework grants the ability to read IL and assembly code, rewrite a method in memory and then use it. For ex- ample, the authors have written methods in memory that send an encrypted e-mail of a users password as they login by changing the control flow of an application.
  • 4. 4 3.3 Assembly Level Again because memory written by the JIT com- piler is rwx, Gray Storm is able to write over it with arbitrary assembly instructions. Custom assembly payloads or MetaSploit payloads can be used and placed over existing methods. Performing this action is as simple as finding the address of a method’s executable memory from Reflection and writing over it with new assembly code. If a payload is longer than the space the current method takes in memory, a user can restructure their assembly code to support a form of hooking. This hooking mechanism allows an attacker to supply an arbitrarily long payload while also allowing an attacker to restore the method as if no code had been changed. The hooking is achieved by creating a 7 byte sequence of the following assembly. 0xB8 0x## 0x## 0x## 0x## //mov eax memory 0xFF 0xD0 // c a l l eax The value of a payload is placed into the memory address that is moved into EAX and then called. In order to restore the original method, the payload needs to be constructed to make room for a payload cleaner that consumes 12 bytes before the payload returns. By creating a cleaner stub with the original return method value the original memory and EIP can be re- stored to the method prelude. This ensures that once a payload runs, it can restore the method as if no changes were made to control flow. Gray Storm includes a shell code editor that allows a user to import arbitrary assembly code. Furthermore, it provides the ability to restore a method’s original code should the attacker want to undo their actions. 3.4 Object Manipulation Within Gray Storm tool there is an attack chain to find and use instantiated objects at runtime. A classes constructor can be discovered using Reflection and a new one can be instantiated locally. Once an arbitrary object is constructed the attack chain finds the location of the man- aged heap, signatures the instantiated object, scans the managed heap and then converts the managed heap object pointers into raw objects [8]. Once objects are referenced locally all of their fields, properties and instance methods can be seen and utilized. 4 CONCLUSION The .NET Framework allows for an attacker to inject into an AppDomain and reflectively learn about the workings of an application. Because Microsoft chose to leave memory readable, writable and executable after a JIT compilation, an attacker is able to control the executing assembly, change control flow and overwrite Method Tables. Through Gray Storm it has been demonstrated that the .NET Framework is insecure by design and an arbitrary application can be changed at an attackers whim. 5 FUTURE WORK There are still improvements that can be made to the aforementioned attack chains. As de- scribed in 3.4, Gray Storm has the ability to hook a method for a one time use. Adding the ability to restore our payload without attacker interaction would be useful and will be imple- mented soon. Furthermore, the proof of concept for this tool was written in x86 assembly and work is currently underway to have full com- patibility with x64. 6 ACKNOWLEDGMENTS The authors would like to thank Jon of Digi- talBodyGuard for assisting in researching .NET attack vectors and teaching them the power of using Reflection for attacking. Through his help they were able to inject Gray Storm successfully into arbitrary .NET applications. Furthermore, Dr. Lynn Ackler, assistant professor at SOU, for constantly being an encouragement and providing the cybersecurity research lab to all computer science students at the university.
  • 5. 5 REFERENCES [1] Elmalki, Ziad. CLR Injection. Jun 2009. http://www.codeproject.com/Articles/37549/CLR- Injection-Runtime-Method-Replacer [2] Intel 64 and IA-32 Architectures Software Developers Manual. Number 325383-053US. January 2015. [3] Jon. Hacking .Net Application at Runtime. In OWASP APPSEC DC, Nov. 2010. [4] Jon. Reflections Hidden Power. May 2002. [5] Microsoft Corporation. .NET Framework 3.5. Compiling to MSIL. [6] Microsoft Corporation. .NET Framework 3.5. Compiling MSIL to Native Code. [7] Ponnupandy, Mercy. Dynamic Code Gen- eration and Code Compilation. Dec 2002. http://www.codeproject.com/Articles/3289/Dynamic- Code-Generation-and-Code-Compilation [8] Timzen, Topher. Acquiring .NET Objects from the Managed Heap. May 2015.