software attacks software attacks dll injection & api patching
TRANSCRIPT
Software attacks
Software Attacks
DLL injection & API patching
Software attacks
What we have seen up to now
• It may be possible to run arbitrary code on a remote machine
• Requires vulnerable software (buffer overflow)
• It is only the beginning: once an attacker has access to the machine, he can do many other things…
Software attacks
Manipulating programs
• This time, we focus on the “second part”• We assume we are somehow capable of
executing some code on the target machine– It could be due to a buffer overflow attack– Or maybe just someone executing our
executable for us (usually the user -> social enginnering attacks, macro viruses, etc.)
Software attacks
Introduction • We use Win32 as target system• So we need to know what is a DLL, how
is organized the memory and how API calls are made
• Before starting: – an executable is a file containing the
program to execute (machine code + various data)
– executables and libraries (EXEs and DLLs) under Windows follow a format called PE (Portable Executable)
– a process is the program running in memory
Software attacks
Win32 memory layout (briefly)
Every process has its own Virtual Address Space. The memory is called “Virtual” because every process has the illusion of having the whole 32-bit (4GB) address space only for its use, and has the illusion of being the only process running in memory (this is valid for other resources as well, such as the registers)
When a process finish its time slice, a context switch is made -> the address space and registers of the new process are loaded
Software attacks
Win32 memory layout (briefly)
The process of translating a Virtual Address to a real physical a address is done in hardware, with the help of the OS (through kernel mode tables called Page Directories and VADs – Virtual Address Descriptors)
Software attacks
Win32 process layout
0x7FFFFFFF (2GB)
0x00000000
Kernel32.dll
0x77000000
0xFFFFFFFF (4GB)
Upper 2GB are reserved for the kernel (not readable nor writeable -> memory access error)
These are protected as well, to help catching errors (NULL)
Upper area of lower 2GB:system DLLs (kernel32, gdi32, etc.)PEB (7ffdf000)
Software attacks
Relocation
• Relocation happens to executable at load time • The loader adjusts pointers to absolute
addresses (code, global variables, constants) using the actual base address at which the executable is loades
• It uses relocation informations stored in the PE
function f (0x00FF)push esp ...
call f (0x00FF)
...0x0000 (start of
file)
PE file
function f (0x004000FF)push esp ...
call f (0x004000FF)
...0x00400000 (load addr)
Process
Software attacks
Relocation• Thanks to VA, relocation is not
necessary in most cases• The linker takes an address as
input (preferred base address, present in the PE header too) and writes absolute addresses taking that adress as base
• If the loader places the PE in memory at that address, no relocation is necessary
• EXEs are always loaded at their preferred base address, and so many system DLLs
• For these PEs, relocation info are stripped
Software attacks
Consequences
• The base address is constant through all processes in a system
• We know where to find functions!!• We use this knowledge to build a little
stub in our address space and load a DLL of our choice in the victim VAD
Software attacks
Injecting a DLL
• The little stubpush [dllName]mov eax, DWORD PTR [LoadLibraryA@4]call eax
Kernel32.dll
(0x796B78FB)LoadLibraryA
Kernel32.dll
(0x796B78FB)LoadLibraryA
Launcher.exe Victim.exe
"zdll.dll"
• WriteProcessMemory and CreateRemoteThread
• But how can we do it? We are in another process – and the stub and dllName must be in victim’s VA
Software attacks
VirtualAllocEx
0x50000000
0x7FFFFFFF
0x00000000
Kernel32.dll
0x796B0000
(0x796B78FB)LoadLibraryA
0x00000000
Kernel32.dll
0x796B0000
(0x796B78FB)LoadLibraryA
Launcher.exe Victim.exe
CreateRemoteThread( 0x796B78FB, //func 0x50000000) //par
LoadLibray("zdll.dll")
WriteProcessMemory"zdll.dll"
zdll.dll
The injection process0x7FFFFFFF
Software attacks
And now?• This is a legitimate process: API for doing
this are well documented, and the approach is known since 1996
• It is used for adding functionalities to existing programs (ex: new look, mouse hooks…)
• But as everything, it can be used for malicious purposes…
• We’ll see three uses: windows subclassing, memory walking and API interception
Software attacks
Window subclassing
• Every widget, graphic component in Windows is a…guess what? A window!
• Even Button, ListBox, etc. are windows, of a pre-defined CLASS
• What is a window class? Is a window that hold every important properties of a window: look, dimension, position, styles, and window procedure
Software attacks
Window ProcedureSo, what is a window procedure? Is a function that is called by the OS when there are messages in the queue for this window
while (GetMessage(&msg,NULL,0,0)){ TranslateMessage(&msg); DispatchMessage(&msg);}
Message Pump Window proc
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ switch (uMsg) { case WM_CREATE: return 0;
default: return DefWindowProc(...); } return 0; }
USER32.DLLWNDCLASS::lpfnWndProc
Software attacks
SubclassingFrom MSDN: “Subclassing is a technique that allows
an application to intercept and process messages sent or posted to a particular window before the window has a chance to process them. By subclassing a window, an application can augment, modify, or monitor the behavior of the window.”
They also add: “However, you cannot subclass a window or class that belongs to another application. All subclassing must be performed within the same process.”If we inject a DLL, code will be executed inthe same process!!
Software attacks
W32.Magister
• Who remember this virus?• It was a rather destructive
one, but after 2 month, on odd days, it did a fun thing:
It made the desktop icons runaway!! Guess how it did it…
Software attacks
Demo (ex6)
Software attacks
Memory walking
• Since the DLL is loaded into the VICTIM address space, we can read EVERYTHING!
• Think about passwords, sensible data• Or about investigating what code is
loaded in the VICTIM address space• Our code lists loaded modules (DLLs,
OCX, and others) in a process of our choice
Software attacks
Demo (ex7)
Software attacks
API intercepting
• This is the most interesting technique: it uses the way function that are in DLLs are called
• Since all APIs in windows are exported using DLLs (kernel32, user32, advapi32, ntdll,…), we can intercept what we want
• Tools like APISPY and BoundsChecker use this technique as an help to debugging
Software attacks
Calling DLLs
call f
.code
jmp 0x77FF0000
.import(IAT)
Exe PE file
Function f
.code
.export
DLL PE file
0x77FF0000
Software attacks
OriginalFirstThunk
TimeDateStamp
ForwardedChains
ImportedDLLName
FirstThunk
AdditionalIMAGE_IMPORT_DESCRIPTO
Rs
…
IMAGE_IMPORT_DESCRIPTOR
INT IAT
"KERNEL32.DLL"
61
CreateFileA
571
LoadLibraryA
48
CloseHandle
Import Table
Software attacks
OriginalFirstThunk
TimeDateStamp
ForwardedChains
ImportedDLLName
FirstThunk
AdditionalIMAGE_IMPORT_DESCRIPTO
Rs
…
IMAGE_IMPORT_DESCRIPTOR
INT
IAT
"KERNEL32.DLL"
61
CreateFileA
571
LoadLibraryA
48
CloseHandle
(0x77E5B6F0) CloseHandle(0x77E5C476) CreateFileA(0x77E5E961) LoadLibraryA
Import Table
Software attacks
OriginalFirstThunk
TimeDateStamp
ForwardedChains
ImportedDLLName
FirstThunk
AdditionalIMAGE_IMPORT_DESCRIPTO
Rs
…
IMAGE_IMPORT_DESCRIPTOR
INT
IAT
"KERNEL32.DLL"
61
CreateFileA
571
LoadLibraryA
48
CloseHandle
(0x77E5B6F0) CloseHandle(0x77E5C476) CreateFileA(0x77E5E961) LoadLibraryA
MyCloseHandle
MyCreateFile
MyLoadLibraryA
IAT patching
Software attacks
An example
• We can intercept all file handling Functions, and make the application read/write files from a path of our own choice
• For our example, we limit the interception at CreateFile(A,W)
• We strip down the actual path and prefix the file name with a path of our own choice (could be even a UNC path, \\1.2.3.4\MyFolder\
Software attacks
An example
Our victim will be a text editor… …but think if that editor is used to write sensible documents! (invoices, business plans, …)
Or if it is a program to change the password file!!
HANDLE WINAPI MyCreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSA, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { string oldFile = lpFileName; string newFile = oldFile.substr(oldFile.find_last_of('\\') + 1); string newPath = "C:\\MiaCartella\\"; newPath += newFile;
return CreateFileA(newPath.c_str(), dwDesiredAccess, dwShareMode, lpSA, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);}
Software attacks
Demo (ex8)
Software attacks
Protections
• BIND programs– Microsoft does this for executables
distributed with Windows– It is not feasible. It’s SP dependent
• Use direct function pointers– Call API directely: example, .NET
runtime read registry values this way– Same drawback as above
Software attacks
Workaround• We can act as a debugger:• Launch the process as a debugee• At load time, parse loaded DLLs, parse Export
Table and locate function location• Place a BP at the entry-point of every
interesting function• At function invocation:
– Disable the entry-point BP– Hijack execution to a function of our choice (in the
injected DLL)– Use a BP at the end of the stub to regain control– Re-enable entry-point BP
Software attacks
ADVAPI32!RegOpenKeyExA:77da229a cc int 377da229b 8bec mov ebp,esp
ADVAPI32!RegOpenKeyExA:77da229a 55 push ebp77da229b 8bec mov ebp,esp
DisableBP(dwRegOpenAddr);SetEip(dwMyRegOpenAddr);
MyRegOpenKeyExA(…, LPCSTR lpKeyName){ log(lpKeyName); LONG result = MyRegOpenKeyExA(…, LPCSTR lpKeyName); __asm int 3; return result;}
mscorsn!ReadRegistryConfig:…79513263 call dword ptr [mscorsn!_imp__RegOpenKeyExA (7951108c)]{ADVAPI32!RegOpenKeyExA (77da229a)}…
EnableBP(dwRegOpenAddr);Continue();
Opcode is restored, control is transferred to MyRegOpenExA
Breakpoint is re-enable, control is transferredBack to the caller…
79513263 call dword ptr [mscorsn!_imp__RegOpenKeyExA]79513269 test eax,eax…
DebuggerVictim
Example
Software attacks
The lesson
• The lesson is: you have to know the internals and the capabilities of your OS:– if you want to program securely at a
low level– if you want to design attacks
• “I’m not a malicious hacker!!”– Know your enemy– Dab
Software attacks
The lesson (2)
• User-based security model is not viable furthermore: programs have the same rights of the user who executes them, so they can do all the things a user can do– Often users didn’t even know what a program
can do!
• Too many users run as administrator, too many programs require admin settings to install and run– Even when a program is executed with
standard rights, the same concept holds!