Software attacks Software Attacks DLL injection & API patching.

33
Software attacks Software Attacks DLL injection & API patching

Transcript of Software attacks Software Attacks DLL injection & API patching.

Page 1: Software attacks Software Attacks DLL injection & API patching.

Software attacks

Software Attacks

DLL injection & API patching

Page 2: 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…

Page 3: Software attacks Software Attacks DLL injection & API patching.

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.)

Page 4: Software attacks Software Attacks DLL injection & API patching.

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

Page 5: Software attacks Software Attacks DLL injection & API patching.

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

Page 6: Software attacks Software Attacks DLL injection & API patching.

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)

Page 7: Software attacks Software Attacks DLL injection & API patching.

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)

Page 8: Software attacks Software Attacks DLL injection & API patching.

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

Page 9: Software attacks Software Attacks DLL injection & API patching.

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

Page 10: Software attacks Software Attacks DLL injection & API patching.

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

Page 11: Software attacks Software Attacks DLL injection & API patching.

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

Page 12: Software attacks Software Attacks DLL injection & API patching.

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

Page 13: Software attacks Software Attacks DLL injection & API patching.

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

Page 14: Software attacks Software Attacks DLL injection & API patching.

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

Page 15: Software attacks Software Attacks DLL injection & API patching.

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

Page 16: Software attacks Software Attacks DLL injection & API patching.

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!!

Page 17: Software attacks Software Attacks DLL injection & API patching.

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…

Page 18: Software attacks Software Attacks DLL injection & API patching.

Software attacks

Demo (ex6)

Page 19: Software attacks Software Attacks DLL injection & API patching.

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

Page 20: Software attacks Software Attacks DLL injection & API patching.

Software attacks

Demo (ex7)

Page 21: Software attacks Software Attacks DLL injection & API patching.

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

Page 22: Software attacks Software Attacks DLL injection & API patching.

Software attacks

Calling DLLs

call f

.code

jmp 0x77FF0000

.import(IAT)

Exe PE file

Function f

.code

.export

DLL PE file

0x77FF0000

Page 23: Software attacks Software Attacks DLL injection & API patching.

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

Page 24: Software attacks Software Attacks DLL injection & API patching.

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

Page 25: Software attacks Software Attacks DLL injection & API patching.

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

Page 26: Software attacks Software Attacks DLL injection & API 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\

Page 27: Software attacks Software Attacks DLL injection & API patching.

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);}

Page 28: Software attacks Software Attacks DLL injection & API patching.

Software attacks

Demo (ex8)

Page 29: Software attacks Software Attacks DLL injection & API patching.

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

Page 30: Software attacks Software Attacks DLL injection & API patching.

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

Page 31: Software attacks Software Attacks DLL injection & API patching.

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

Page 32: Software attacks Software Attacks DLL injection & API patching.

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

Page 33: Software attacks Software Attacks DLL injection & API patching.

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!