Reverse Engineering
Class 5
Malware Analysis
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 1
Malware Analysis
Something strange?
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 2
Malware Analysis
● Process injection
● Hide and evade audit logs
● Bypass endpoint firewalls with application
filtering
● Steal information from the injected process
● Change session (non-interactive session →
interactive session)
● Screenshots
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 3
Malware Analysis
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 4
Malware Analysis
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 5
Malware Analysis
● Goals
● Move malicious code to the target process
● Create a new thread in the target process
that executed malicious code
● Avoid interruptions or data corruption in the
target process
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 6
Malware Analysis
● Process injection techniques (Windows)
● CreateRemoteThread
● Asynchronous Procedure Call
● Debugging API
● Process injection techniques (Linux)
● Debugging API (ptrace)
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 7
Malware Analysis
● CreateRemoteThread (Windows)
● OpenProcess
● Handle to manage a remote process
● VirtualAllocEx
● Allocate memory to the remote process
● Write and execute permissions
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 8
Malware Analysis
● CreateRemoteThread (Windows)
● WriteProcessMemory
● Write remote process memory
● Malicious code to inject
● CreateRemoteThread
● Create a new thread in the remote process
and make it execute previously written
memory
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 9
Demo 5.1
Process injection with CreateRemoteThread
(Windows)
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 10
Malware Analysis
● Asynchronous Procedure Call (Windows)
● Windows API to queue asynchronous calls to
threads
● When thread is in “alertable” state (I.e.
sleep), it will attend the call
● Call is to an arbitrary address, chosen by
the one who equeues it
● When calls ends, thread context is
automatically restored
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 11
Malware Analysis
● Asynchronous Procedure Call (Windows)
● A handle to the victim process and to a
thread in it are obtained: OpenProcess,
CreateToolhelp32Snapshot, OpenThread
● Memory is allocated in the process and
executable code is written: VirtualAllocEx y
WriteProcessMemory
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 12
Malware Analysis
● Asynchronous Procedure Call (Windows)
● An APC call is enqueued with
QueueUserAPC
● It’s important that injected code creates a
new thread to continue execution; thread that
handles the APC has to return to its normal
execution
● If an application thread is definitely
interrupted, instability may be caused
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 13
Malware Analysis
● Debugging API (Windows)
● Allocate memory and write code to inject into
the process (remotely)
● Debug the target process
● Debugger is attached to a thread
● DebugActiveProcess /
WaitForDebugEvent / ContinueDebugEvent
● Save the attached thread context (I.e. save
registers values in the injector process)
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 14
Malware Analysis
● Debugging API (Windows)
● Attached thread is set to execute injected
code
● A new thread is created from injected code
● Control returns to debugger and the attached
thread original context is restored
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 15
Malware Analysis
● Debugging API: ptrace (Linux)
● Similar to the technique described for
Windows
● Debugging API in Linux (Unix): ptrace
● Read / write a thread context (registers)
● Read / write process memory
● Intercept every signal to the debugged
process
● Run the process step-by-step
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 16
Malware Analysis
● Debugging API: ptrace (Linux)
● Problem:
● It’s not possible to remotely allocate
memory to a process
● It’s not possible to remotely create a
thread on a process
● Solution:
● Hijack a thread and make it do it on our
behalf
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 17
Malware Analysis
● Some ptrace primitives
● PTRACE_ATTACH
● PTRACE_PEEKDATA
● PTRACE_POKEDATA
● PTRACE_SYSCALL
● PTRACE_CONT
● PTRACE_GETREGS
● PTRACE_SETREGS
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 18
Malware Analysis
● Debugging API: ptrace (Linux)
● Attach to the target process
● Resolve mmap and __clone virtual
addresses (libc)
● Libc base in /proc/<PID>/maps
● Resolution reading memory (ELF format)
● Workaround: resolve offset with dlsym and
dladdr inside the injector and use it on the
injected process
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 19
Malware Analysis
● Debugging API: ptrace (Linux)
● Save attached thread context to restore it at
the end of the injection
● We want the injected process to continue
execution normally
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 20
Malware Analysis
● Debugging API: ptrace (Linux)
● Modify attached thread context (hijacked):
● RIP → mmap / __clone address
● Other registers → function parameters
(according to the x86_64 ABI)
● Modify the stack: 16 bytes alignment (ABI)
and return address = 0x0.
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 21
Malware Analysis
● Debugging API: ptrace (Linux)
● Continue the process and let the called function
execute. When returning, instruction at address 0x0
will be tried to execute and a signal is going to be
sent to the process (invalid address)
● Given that the injector is a debugger, receives the
signal first and can handle it
● Signal is discarded, instead of passing it to the
debugged process
● Modify the attached thread context to execute
another function or restore it to continue normal
execution
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 22
Malware Analysis
● Debugging API: ptrace (Linux)
● Function calls in the remote process:
● Allocate memory for the executable buffer
(injected instructions), with mmap
● Allocate memory for the stack of the
thread that is going to execute the injected
buffer, with mmap
● Create a new thread with __clone
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 23
Malware Analysis
● Debugging API: ptrace (Linux)
● How registers have to be set for each call?
● Application Binary Interface (ABI)
● Tip: debug a simple example what uses
libc API and trace it until the syscall is
executed
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 24
Demo 5.2
Process injection with ptrace (Linux)
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 25
Malware Analysis
● Limits of previous techniques
● Security model in Windows
● Access Token – object that describes the security context
of a process or thread (GetTokenInformation)
● When user logs into the system, an access token is
assigned. Every process that the user executes have
this token.
● Contains user account identity and its groups: SIDs
(Security Identifiers)
● Contains privileges for administrative tasks (I.e. reboot
the system, change date, load drivers, etc.)
● One thread may eventually impersonate a different user
and use its access token
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 26
Malware Analysis
● Limits of previous techniques
● Security model in Windows
● Security Descriptors: security information
tighted to each Securable Object
● Owner and primary group
● DACL – discretionary access (to specific
users or groups)
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 27
Malware Analysis
● To invoke OpenProcess and other debugging APIs in a
process from a different user, “SeDebugPrivilege” privilege
has to be enabled in the Access Token
● Only administrative accounts should have this privilege
available to be enabled
● To debug processes from the same user this privilege is
not needed
● From a defensive point of view, this reminds the
importance of not executing with administrative accounts
or, in that case, impersonate non-privileged users
● Model brings granularity to assign non-privileged
accounts the privileges needed
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 28
Malware Analysis
● Limits of previous techniques
● Security model in Linux
● Before kernel 2.2, security module
consisted of privileged and non-privileged.
A privileged process had control over the
whole system.
● There is software that legitimately requires
privileges. In example, a DNS server has
to listen incoming connections in a low
port (53)
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 29
Malware Analysis
● Limits of previous techniques
● Security model in Linux
● However, under the assumption that the
process may be exploited, damage
mitigation is needed.
● “capabilities” allow more privileges
granularity for processes
● “capabilities” are tight to execute binaries.
A process that drops capabilities in
runtime, cannot re-acquire them later.
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 30
Malware Analysis
● Limits of previous techniques
● Security model in Linux
● To arbitrary debug processes (from
different users), CAP_SYS_PTRACE
capability is required
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 31
Malware Analysis
● Analyze external libraries and functions that
malware uses may bring an idea of its behavior
● I.e it’s likely that if debugging APIs are used,
malware has process injection capabilities
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 32
Malware Analysis
● Getting familiar with DLLs in Windows
● [Link]
● Base DLL. Memory, files and hardware
management. Imported by every Windows
executable.
● [Link]
● Access to Service Manager and Registry
● [Link]
● Graphic interface components (buttons, scroll
bars, text areas, etc.).
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 33
Malware Analysis
● Getting familiar with DLLs in Windows
● [Link]
● Graphics management. User space library. [Link] in
kernel.
● [Link], Ws2_32.dll y [Link]
● Networking libraries (sockets, HTTP connections, etc.)
● [Link]
● C/C++ runtime. Abstraction layer on top of Windows API.
Memory allocation, files, strings, etc.
● [Link]
● Not documented but present in every process. Interface to
kernel.
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 34
Malware Analysis
[Link] is interesting because it
includes:
● Kernel structures
● Not documented APIs, that
enable extra functionality (or
high level APIs restrictions
bypass)
● Avoid import “suspicious”
functions
Eventually malware may execute
direct kernel syscalls, based on
what [Link] does (syscalls
interface is not documented).
Image from “Practical Malware Analysis: The
Hands-On Guide to Dissecting Malicious Software”
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 35
Malware Analysis
● How does a keylogger work?
● Challenge: mange a huge amount of data.
● API SetWindowsHookEx
● Malware installs a hook (callback) for a specific event
● In case of a keylogger, that event is
WH_KEYBOARD_LL
● Hooks can be global or constrained to a specific thread
● This technique can be used to inject DLLs in
processes: callback (implemented in a DLL) is called in
the context of the process that generates the event
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 36
Malware Analysis
● How does a keylogger work?
● Limits
● Discretionary security (per user or group) is not enough:
what happens if a malware downloaded from the
Internet gets executed by an administrative user? What
happens if the Internet browser is remotely exploited?
● Mandatory security: securable objects and processes
have an assigned integrity level
● A low intergrity process cannot read or write a high
integrity object
● A low integrity process cannot install a keylogger
hook
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 37
Malware Analysis
● COM – Component Object Model
● Object oriented communication framework
● Communication within the same process, between
processes or between processes on distributed
hosts (DCOM)
● Bindings for different languages. Example: from
VBAScript a function on a DLL (developed in C++)
can be invoked
● Used by Internet Explorer and Microsoft Office
among others
● Parameters marshalling. Data types normalization.
Objects reference counting.
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 38
Malware Analysis
● COM – Component Object Model
● Stable ABI, independent from the language
and compiler
● Communication happens on top of low
level mechanisms
● In example, DCOM can used SMB and
TCP/IP as transport
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 39
Malware Analysis
● COM – Component Object Model
● Works in client-server mode
● Server exposes an object (reusable component)
to be used by different clients.
● Object implements one or more interfaces
(IIDs). I.e. IWebBrowser2. Object concrete
implementation (class, identified by a CLSID)
can be a DLL or an executable binary. I.e.
Internet Explorer.
● Client consumes services offered by the object
calling its methods or properties.
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 40
Malware Analysis
● COM – Component Object Model
● A client locates an object published in the
Registry
● Interfaces and classes are identified by GUIDs
(unique numbers 128 bits long)
● HKLM\SOFTWARE\Classes\CLSID\ and
HKCU\SOFTWARE\Classes\CLSID
● OleInitialize, CoInitializeEx, CoCreateInstance
● At implementation level, functionality is provided
by DLLs like [Link], [Link] and
technologies like ActiveX
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 41
Malware Analysis
● COM – Component Object Model
● Methods on interfaces always return HRESULT
to indicate the call result. Return values go
through pointer parameters. Parameter types is
specified with [IN] and [OUT] in the
documentation.
● An object always implements IUnknown interface
● This interface allows to modify the object
reference counter (AddRef, Release)
● Obtain pointers to interfaces implemented by
the object (“casting”)
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 42
Malware Analysis
IWebBrowser2* pObjBrowser2;
CoCreateInstance(…);
pObjBrowser2->Navigate();
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 43
Malware Analysis
EAX = pointer to the object (heap)
In the first bytes of the object memory there
is a pointer to the class vTable. vTable is a
table of pointer to the class methods.
In the following bytes object attributes are
located.
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 44
Malware Analysis
ECX = pointer to object’s class vtable
(IWebBrowser2 interface)
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 45
Malware Analysis
● vTable is not necessarily in a fixed address
because the DLL with the object
implementation may be located at any
virtual address range
● vTable values (pointers to methods
implementation) may change for the same
reason
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 46
Demo 5.3
COM object call (Windows)
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 47
Malware Analysis
typedef struct tagVARIANT {
union { Structure to represent “generic”
struct __tagVARIANT { parameter types. Have more overhead
VARTYPE vt;
WORD wReserved1;
but the advantage that data type may be
WORD wReserved2; unknown in compile time.
WORD wReserved3;
union { VARTYPE vt value allows to identify the
LONGLONG llVal; parameter type and correctly interpret
LONG lVal; the value.
BYTE bVal;
SHORT iVal; Objects that implement IDispatch
FLOAT fltVal; interface allow instrospection: query
DOUBLE dblVal; methods and properties in runtime and
... invoke them. This interface requires
}
generic parameters and return value,
...
} because they depend on each
} implementation.
} VARIANT, …;
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 48
Malware Analysis
● Rootkits
● Malware that manages to escalate privileges and
execute in ring0 (I.e. load a driver)
● It’s necessary to debug kernel to detect it
● May modify kernel structures to hide from user
space (I.e.: remove itself from the process list or
hide listening ports)
● Evades antivirus
● Has global system visibility: processes memory and
syscalls
● Hooks sys_call_table, SSDT or interruption vector
● May write read-only memory
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 49
Lab
Lab 5.1: Modify Demo 5.1 code (Create
Remote Thread injection) to call
“GetCommandLine” function in the injected
process and save the result in a file.
Lab 5.2: Modify Demo 5.2 code (ptrace
injection) to call “getpid” function in the injected
process and save the result in a file.
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 50
Lab
Lab 5.3: Modify Demo 5.2 code (ptrace
injection) to intercept any function call on the
injected application and dump it to a file.
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 51
References
● [Link]
createremotethread-for-dll-injection-on-windows
● [Link]
es/library/windows/desktop/ms682437(v=vs.85)
.aspx
● Practical Malware Analysis: The Hands-On
Guide to Dissecting Malicious Software
Reverse Engineering | Class 5 | Martin Balao | [Link]/reverse | v1.0 EN | CC BY-SA 52