Archive for the ‘IDA-Pro’ Category

# weakness of PAGE_GUARD or new Windows bug (XP/Vista 32/64 SP1)

simple, but effective system independent anti-debug trick based on well-documented APIs and does not involve assembly inline (means: it could be implemented in pure C). also it works as anti-dump sensor.

caution: I would recommend do _not_ use this thick in production code, because it’s based on the bug (two bugs actually: one in Windows, another in OllyDbg), which could be fixed at any moment. however, noting terrible happens if the bug would be fixed – the application just could not detect debugger/dumper.

in passing: I found this bug working on the project for a spectrography cherry group, well, not a cherry actually, but I prefer to keep the real name if it under the mat, anyway it’s all about Ciscar Fon – my first love, a gothic type, very kinky and yet creative.

in a nutshell: the whole idea based on PAGE_GUARD attribute. SDK says: “any attempt to access a guard page causes the system to raise a STATUS_GUARD_PAGE (80000001h) exception and turn off the guard page status… if a guard page exception occurs during a system service, the service typically returns a failure status indicator“. wow! how I like these words: “typically”, “usually”, “normally”… they say nothing, but at the same time they say everything!!! just read between the lines…

ReadProcessMemory: normally, /* I mean _normally_ */ ReadProcessMemory() returns error if it meet a page with PAGE_GUARD attribute. does it make sense? of course! but, _normally_ does not mean “every time”. Windows has a bug (I tested W2K SP4, XP SP3, Vista SP0 and Vista 64bit SP1 – they are all affected).

the bug: if PAGE_GUARD page is created by VirtualAlloc() call, ReadProcessMemory() turns off the guard page status without any exception and returns a failure status indicator. however, the second ReadProcessMemory() call returns a positive status (because PAGE_GUARD was turned off), so when the application will try to access to that page – there will be no exception (as it’s supposed to be), because there is no guard anymore.

the sensor: it’s easy to create a sensor to detect dumpers. allocate a page with PAGE_GUARD attribute and check it from time to time: just install SEH handler and read the content. no exception means we’re fucked, oh, sorry, dumped. I tested PE-TOOLS and other popular dumpers and they all were detected.

demo: to demonstrate the bug, I wrote two simple applications. one – “protected-like” application, another – dumper-like application. please download the sources and binaries.

“protected” application (PAGE_GUARD_BUG.c) is very simple, basically it just calls VirtualAlloc(,,,PAGE_READWRITE | PAGE_GUARD), displays the address/PID, waits for pressing ENTER and attempts to read the content of the allocated block. there is no SEH handler, so if an exception happens you will see the standard Windows message box.

p = VirtualAlloc(0, 0×1000, MEM_COMMIT, PAGE_READWRITE | PAGE_GUARD);
printf(“run turnoff.exe %d %d twice and press enter”, GetCurrentProcessId(), p);
gets(buf); printf(“result: %x\n”, *p);

and the “dumper” (turnoff.c ) just calls ReadProcessMemory() and displays the result:

h = OpenProcess(PROCESS_ALL_ACCESS, 0, atol(arg_id));
x = ReadProcessMemory(h, (void*)atol(arg_addr), &buf, 0×1, &n);

oh, here we go. follow me, please!

1) run the protected app (“$start PAGE_GUARD_BUG.exe“);
2) it displays ID/addr, like: id:1216 addr:4325376;
3) press right now;
4) ops! exception! this means: PAGE_GUARD works!!!
5) run the protected app again (“$start PAGE_GUARD_BUG.exe“);
6) it displays ID/addr, like: id:1212 addr:4325376;
7) run the dumper, passing ID and addr (“$turnoff.exe 1212 4325376“);
8) it says: “satus:0, bytes read: 0″ (means: ReadProcMem failed);
9) but! if you switch to PAGE_GUARD_BUG.exe and press ENTER you will see no exception (means: PAGE_GUARD was turned off);
10) if you run the dumper twice (of course without pressing ENTER) it will displays: “satus:1, bytes read: 1″ (means: there is no PAGE_GUARD anymore);

nice trick, it’s it? but actually it was just a little warming-up. the real tricks are coming.

NOTE: if PAGE_GUARD attribute is assigned by VirtualProtect(), Windows respects the attribute and ReadProcessMemory() fails, leaving PAGE_GUARD turned on.

debuggers: what happens if a debugger meet PAGE_GUARD page? the answer is: there will be no exception, the debugger just turns PAGE_GUARD off, processes the content and forgets to return PAGE_GUARD back.

demonstration: to demonstrate this nasty behavior I wrote a simple program PAGE_GUARD_DBG.c, download it, please. and follow me. the source code is easy to understand:

push 0×102 ; PAGE_READONLY | PAGE_GUARD
push MEM_COMMIT
push 0×1000
push 0
call ds:[VirtualAlloc]
mov eax, [eax]

execute it step-by-step, make step over the VirtualAlloc() call and display the content of the allocated memory block (for example, in IDA-Pro press , eax, ENTER and to go back). continue tracing, and… ops! where is our exception?! there is no one!!!

OllyDbg is even worse. it automatically resolves memory references displaying the content in the right column, so we don’t need to go to the dump window nor pressing CTRL-G… just trace it and the debugger will be detected, since there will be no exception!!!

IDA-Pro: well, what about if we just run the program under debugger? just run, no trace! IDA-Pro triggers an exception: “401035: A page of memory that marks the end of a data structure such as a stack or an array has been accessed (exc. code 80000001, TID 1312)” and offers to pass the exception to the application. in this case the debugger will be _not_ detected.

OllyDbg: the standard de-facto debugger stops when the application accesses PAGE_GUARD, giving the message “Break-on-access when reading” in the status bar, but Olly does not offer us to pass the exception to the application. even we go to options->exceptions and add 0×80000001 (STATUS_GUARD_PAGE) exception to the list, Olly will ignore it! guess, PAGE_GUARD is just a part of “memory-breakpoint” engine, so no way to pass PAGE_GUARD exception to the application, so it’s easy to detect the debugger. (I tested OllyDbg 1.10).

Soft-Ice: it does not display the content of PAGE_GUARDED pages, so it could not be detected by this way. in other hand, keeping the impotent content under PAGE_GUARD makes debugging much harder. we can’t perform full memory search, we can’t find cross references… we’re blind.

the love triangle: PAGE_GUARD, Windows and OllyDbg: Windows has a bug, Olly has a bug, so... how were supposed to debug?!

the love triangle: PAGE_GUARD, Windows and OllyDbg: Windows has a bug, Olly has a bug, so... how we're supposed to debug?!

 

# IDA-Pro steals RIP — introduction in relative addressing

intraarterial injection: i was involved into a project on design a software-level protection, based on anti-dbg tricks that should work in 32- and 64-bit environment causing no conflict with legal apps. also, my shell-code locator has to learn how to recognize x86-64 exploits, so… I took a deep breath and dived into 64-bit word. well, I’m not newbit here, but digging up the anti-dbg tricks working everywhere sounds like a challenge. ok, anti-dbg tricks, shell-codes… good point to begin with.

kotal: x86 does not allow to address EIP register directly (PDP-11 does), but supports relative addressing in the flow control commands (“the” means “all”), for example: CALL L1 it’s a relative call. in the machine representation it looks like: E8 61 06 00 00, where E8h is opcode of CALL and 61 06 00 00 – a relative 32bit signed offset of the target, calculated from the _end_ of the CALL.

it’s very important for shell-codes, because it gives them ability to work being loaded at any offset. for protections it’s useful well. to prevent dumping – just allocate the memory on the heap and copy your procedure there. no dumper is able to create a workable PE image out of heap!

drawbacks: aside of benefits of relative addressing it has its own disadvantages. guess, what happens if we copy our function which calls the function we can’t copy (for example, API). the delta between CALL and the target will be changed, forcing us to recalculate all relative addresses, or… (turn your mind on) start to use absolute addressing, for example: mov eax, offset API_func/CALL eax;

home and dry: x86-64 does not allow to use RIP (former EIP) as a general purpose register (MOV RAX, RIP does not work), but it supports relative addressing almost everywhere (let me to quite the Intel manuals:”RIP-relative addressing allows specific ModR/M modes to address memory relative to
the 64-bit RIP using a signed 32-bit displacement. This provides an offset range of -/+2GB from the RIP
“). what it does mean?! for shell-code writers it means a lot!!! from now on we don’t need in GetPC subroutine (usually, CALL L1/L1:POP r32) and can use RIP directly. and this is the part where we meet the problem of the stolen RIP.

anaphylactic shock: please, consider the following code. this is how IDA-Pro 5.5 disassembles it. remember: it’s a piece of a real shell-code, so, concentrate your mind into fuming acid and do not miss the point (see the picture bellow as well):

.code:0000000000401000 start proc near
.code:0000000000401000 mov ecx, 69h
.code:0000000000401005 jmp short loc_40100C
.code:0000000000401007
.code:0000000000401007 loc_401007:
.code:0000000000401007 nop
.code:0000000000401008 xor [eax+ecx], cl
.code:000000000040100C
.code:000000000040100C loc_40100C:
.code:000000000040100C lea rax, loc_401013
.code:0000000000401013
.code:0000000000401013 loc_401013:
.code:0000000000401013 loop loc_401007
.code:0000000000401015 mov r9d, 0

how do you like it?! ok, let me to be more specific. how do you like the line: “lea rax, loc_401013″?! what?! did you say: “looks clear!” hello no!!! look closely!!! Option -> Text representation -> Number of opcode bytes -> 9. do you see _now_ what IDA-Pro hides from us?!

.code:000000000040100C 48 8D 05 00 00 00 00 lea rax, loc_401013
.code:0000000000401013 loc_401013:

oh, my unholy cow!!! “LEA RAX, loc_401013” turns out to be “LEA RAX, [RIP]“, thus we’re dealing with position-independent code. in a way, IDA-Pro is correct. she is just calculates RIP on the fly and replaces it by the effective offset. but, we – hackers – want to know if the code is position independent or not!!!

breakdown: HIEW also replaces RIP by effective offset. please consider the following line: 0040100C: 488D05000000001 LEA RAX, [000401013]

ok, do you want to get high? well, let’s do it, ppl!

00000000: 488D0500000000 lea rax,[7]
00000007: 488D0500000000 lea rax,[00000000E]
0000000E: 488D0500000000 lea rax,[000000015]

the same opcodes produce different targets, how funny!!! of course, it’s an opcode of LEA RAX, [RIP] command and I would like to have an option which enables/disables showing RIP, because I do need in very much!!!

updated: Igor Skochinsky pointed out (see his comment below) that IDA-Pro allows us to show RIP (Options -> Analysis options -> Processor specific analysis options -> Explicit RIP-addressing). ok, lets enable it and see what happens:

.code:000000000040100C loc_40100C: ; CODE XREF: start+5j
.code:000000000040100C lea rax, [rip+0]

well, say hello to “RIP”! it’s explicated now, but… the rest of the code is almost damaged and unvoyageable (means: inconvenient for navigation):

.code:000000000040101B lea r8, [rip+0FDEh] ; “x86-64 program!”
.code:0000000000401022 lea rdx, [rip+0FEEh] ; “hello world!”
.code:0000000000401029 mov rcx, 0 ; hWnd
.code:0000000000401030 call qword ptr [rip+2016h]
.code:0000000000401036 mov ecx, eax ; uExitCode

we see relative offsets like 0FDEh, 0FEEh, 2016h, etc. they’re red colored (means: IDA-Pro does not recognize these offsets) and if we move cursor to the constant – we can’t jump by ENTER and we need to calculate the target address manually. so, the problem is still unsolved.

in passing: look at the encoder again. don’t you think that it damages the loop?! ok, lets trace the code with any debugger or with our own mind if we have no 64-bit debugger under our hands.

“loop loc_401007″ has E2h F2h opcode. in binary representation F2h is “011110010″, so the lowest bit is zero, thus, when ECX = = 1, the target of loop will change from 401007h to 401008h (401007h ^ 1 = 401008h). as result – NOP will be skipped. of course, it might be INC EBX (opcode 43h) – in that case, EBX would be increased not by ECX (as it’s expected), but by (ECX – 1). how interesting…

well, when ECX = = 0, LOOP just does not pass the control to the target, so everything works fine.

updated: Sol_Ksacap (from www.wasm.ru) pointed out that (let me to quote him): “the target of loop will indeed change, but there won’t be any loop – “loop” instruction first decreases RCX, and only then checks if it’s zero“. and he is definitely right. this post was written in hurry. sorry for the mistakes I made and big thanks all guys who pointed it out.

off the record: in normal shell-codes you probably meet something like LEA EAX, [RIP-1] (opcode: 8B05FFFFFFFF), since commands with the positive offsets have zeros in opcodes and shell-codes do not like zeros very much (because of ASCIIZ, where Zero is a string terminator).

updated on:
Wed, Juli-15: enable-RIP option in IDA-Pro, loop patching bugs;

an example of real 64bit shell-code with hidden RIP

an example of real 64bit shell-code with hidden RIP

 

# IDA-Pro//BOCHSDBG plug-in bug: lack of 16bit support

16bit code is obsolete today, it’s nearing the end of its exile, the rogue’s march is playing despite the fast that 16bit programs are alive and millions users continue using them, being scared by the fact that x86-64 does not support 16bit anymore and even 32bit NT/XP has a very feeble DPMI host.

ok, let’s get down to business. some people want to debug 16bit applications for different reasons. IDA-Pro supports 16bit MS-DOS/DPMI applications quite well, and states that BOCHSDBG Plug-in support them too. (NOTE: IDA 5.3 and lower supports only win32 Debugging Engine, thus, you can’t debug 16bit apps with it).

the problem is: BOCHSDBG Plug-in does not support neither 16-bit MS-DOS/EXE nor 16bit code snippets. whether it’s 32bit or 16bit segment, BOCHSDBG plug-in threats it as 32bit, executing code in 32bit mode. not wonder that we get an unexpected result. for example, PUSH 1234h decreases ESP by four(!) instead of two! the worst thing is: 16bit and 32bit modes are very different. 8Bh 00h is “mov eax, [eax]” in 32bit mode and “mov ax, [bx][si]” in 16bit!

in the mean time: BOCHSDBG supports 16bit code well by itself. just to prepare an image, load in into BOCHSDBG and you the integrated debugger (a simple console one, kind of gdb). don’t touch IDA-Pro! you don’t need at all for this particular operation (IDA-Pro team is going to support 16bit code snippets, but it’s going to take time, the next version will probably just check the segment size and refuse to debug it with BOCHSDBG Plug-in if it’s 16bit).

if you’re not familiar with GDB or want to know more about debugging 16-bit apps with BOCHSDBG just leave me a comment and I will write a special post about it, sharing my own BOCHS image with all necessary tools installed (free and legal).

closing remarks: 16bit code became a quite strong anti-debug trick by itself, because the modern hacker tools do not support it at all :(

an attempt to debug 16bit code with IDA-Pro 5.5/BOCHSDBG Plug-in

an attempt to debug 16bit code with IDA-Pro 5.5/BOCHSDBG Plug-in

 

# IDA-Pro 5.5 has been updated, fixed — Bochs plug-in unaligned PE bug

in a nutshell: IDA-Pro 5.5.0.925 has been updated on July-01/2009 in order to fix a bug in BOCHSDBG plug-in. from now on it supports unaligned PE files (see definition below). if you want to get the updated version, send your identification (the ida.key) to support@hex-rays.com.

nude statement: I don’t like IDA-Pro Debugger. it’s very limited, devilish uncomfortable and embarrassing. it has its own benefits, none the less, but for me OllyDbg is much better. every man has his taste – opinions differ.

death notice: OllyDbg/Soft-Ice (like any other x86 debugger) is very limited. it could be detected, it could be broken. it does not support tracing of a self-traced program and there is no workaround — no script nor plug-in to fix it. it’s nature of x86 CPU. the same story with DRx registers. virtualization and emulation is the only way to hack strong protections (oh, come on! as if you can’t break an emulator, whose behavior is pretty different from native CPU).

brutal facts: what do we have?! is there any decent emulator?! well, x86emu (plug-in for IDA-Pro) is extremely limited. BOCHSDBG is good enough to debug MBR or OS loader, but… how we’re supposed to debug applications/drivers, working _below_ the Operation System?! the same story with VMWare/WinDbg and QEMU/GDB. so, in essence there is no decent emulators, except for internal products like McAfee EDebug (very good tool, but only for home consumption, “home” means “McAfee”).

beam of hope: IDA-Pro debugger had been significantly improved since 5.4 and the most dramatical change is BOCHSDBG plug-in supporting win32 PE debugging. what does it mean and how it works? well, to answer the first question: we got what we were waiting for a looong time. yeah, there was BOCHS, but it’s impossible to debug code snippets directly into BOCHS. the only way to do it – create an image of a tiny operation system and put a snippet there. CPU starts in real 16 bits mode, while win32 programs expect to see 32-bit protected mode with flat address space – the minimum requirements to debug code snippets, but it’s not enough to hack real applications!

the next step is to create win32-like environment. at least we need to emulate fundamental system structures (like PEB) and engines (SEH for example) not mention basic API set. it has been hell of a job (or, may be, a job in hell). and this job has been done by Elias Bachaalany, he is our hell-guy – very talented brick from the eastern shore of the Mediterranean Sea. not wonder that he is a clever cat!

a mint of intrigue: it was excitement from the first sight when I read Ilfak’ post “Bochs Emulator and IDA?“. it was just awesome! at that moment my company provided me a license for IDA-Pro 5.3, but it was too old to be updated for a free, so I kicked up my heels. McAfee provided me a license as well (Danke schön to the director of IPS research of Avert Labs, it was very kind of him and maybe I will find myself in his team based in Santa-Clara). but… it was IDA-Pro 5.3 – the original CD, shipped to Moscow McAfee office, hosted in the biggest building in Europe – Naberezhnaya Towers, but I was unable to get the updates because of security policies of McAfee. I had no access to the internal network and the sardonic Firewall did not allow to go outside. what’s a piggishly! only when IDA-Pro 5.5 has been released, I got the updates directly from hex-rays.com, sitting in Macrovision office and thinking that even in my village Internet is faster (I own 10 Mbytes link, but an average speed is 2 Mbytes, but it’s more that enough to fit my needs).

collapse of plans: I started testing the new plug-in, trying to debug programs (malware mostly) that I was unable to debug with OllyDbg and the old IDA-Pro debugger. the first impression was: wow! it’s cool! it’s easy to trace self-tracing code, “software” breakpoints do not changed the content… well, I felt like I reached the golden gates (or it was Golden Bridge?) and was about to dine with Mohammed, happy hunting ground – Elias made the best of both worlds, but… better to reign in hell than serve in heaven. BOCHSDBG plug-in is a great tool, yet it’s all wrong. the whole design is wrong. it’s easy to break the debugger.

for example: it traces programs by BOCHS virtual CPU engine. the very engine is used by the debugged program, so… no problem to detect the debugger, yet it’s harder than beat a non-virtual one. (now I’m working on anti-debugging tricks some of them will be posted here, some – for commercial purposes).

the facts: when you choose Loader Type -> PE in BOCHS configuration message box, the plug-in prepares a virtual image and loads PE file there. so, we should expect a lot of problems, because it’s almost impossible to design a decent 3rd party PE Loader. the problem is: MS PE Specification is not accurate and MS does not follow it. take Section Alignment for example. according to MS PE specification, the minimal Section Alignment == PAGE_SIZE, but win/32 supports much smaller values as well (win/64 does not) and the smallest alignment, supported by standard MS Linker, is 10h. lets come to terms to call these files “unaligned PE” – it’s not a good term, because the files are still aligned, yet the align value is much smaller than the specification requires, but it’s just a term :-)

IDA-Pro 5.5.0.95 BOCHSDBG Plug-in does not support unaligned PE files, and generates an exception on any writing attempt, even if the section is writable (in fact, even the section is not writable, the system PE loader makes _all_ sections writable, regardless of the attributes – but I will keep this feature to another post). just a few people have a chance to meet an unaligned PE, because these files are not common for commercial applications, but malware use this trick quite often in order to be smaller, and I met the problem on the second day of using IDA-Pro BOCHSDBG Plug-in.

in the can: to demonstrate the problem I created a very simple file. download it or see the source below:

int mem; char *txt=”[OK]“;
__declspec(naked) nezumi()
{
__asm{ mov [mem], eax }
MessageBox(0, txt, txt, 0); ExitProcess(0);
}

to make it, run “nmake make” or use the following command lines:

$cl.exe /c /Ox ida-bug_bochsdbg-16.c
$Link.exe ida-bug_bochsdbg-16.obj /ALIGN:16 /ENTRY:nezumi /SUBSYSTEM:WINDOWS KERNEL32.lib USER32.lib

ignore the linker warning “LiLNK4108: /ALIGN specified without /DRIVER or /VXD; image may not run” — image works fine on 32-bits editions of NT, W2K, XP, S2K3/S2K8, Vista (64-bits editions probably will not run it, but I have not checked it by myself, if you have 64-bits editions of Windows under your hand, please test it and post your comment here, thanks!)

as you can see, unaligned exe works fine, OllyDbg and local IDA-Pro debugger have no problem with it, but… go to Debugger menu, click “Switch Debugger”, select “Local Bochs debugger” and run it by F9 or try to trace step-by-step.

ops!!! an exception on a write attempt (see the pic below), accessing “mem” variable, which belongs to .data section, which is writable. remove “/ALIGN:16” key from the linker arguments, rebuild the program and try to debug it again. now it works fine! but… we can’t rebuild closed source program!!! so, it’s a problem and now it’s fixed. just ask the support for the updated version.

updated on: Sun, July 05, 04:44: grammar fix

IDA-Pro 5.5.0.925, BOCHSDBG, unaligned pe, impact area

IDA-Pro 5.5.0.925, BOCHSDBG, unaligned pe, impact area

 

# self-replicated processes

adown the stream of time, back in the old days… well in advance, after a while now and again everything will come in its proper time to put the clock back, for some time past – old UNIX tricks work! nothing new under the sun!

taking self-replication processes for example! Morris used this technique in his worm. the idea as simple as brilliant: a process forks every second, well, maybe not every second, but pretty often. what’s the point?! there’re two points guys! first! by default a debugger is able to debug only debugged process. the process, created by the debugged process is not debugged as well, like le vassal de mon vassal n’est pas mon vassal (“the vassal of my vassal is not my vassal“). so what?

let’s try to write a very simple program and try to debug it with Olly, IDA-Pro and Soft-Ice. we will see who is the beast and why I want to port Soft-Ice on Vista. this is the program. type it or download source and binary.

main(c, v) char **v;{if (–c) printf(v[1]), execlp(v[0], v[0], &v[1][1], 0);}

it displays the argument passed via command line cutting one char every iteration. load the execlp.exe into OllyDbg, now \Debug\Arguments\ and type something like “- – - * – *”. restart the debugger by CTRL-F2 to apply changes and start the debug.

ops!!! every time when the debugger steps over 00401022!call execlp it just loses control, allowing the debugged program to fly out! did you expect something else? like what?! no way!!! le vassal de mon vassal n’est pas mon vassal!

btw, IDA-Pro 5.3 has a bug. the debugged process attached to a new console, but all children process creates another console. the secondary console is closed when the process is terminated, but the first console is still open even the debugger is terminated. OllyDbg has no this bug.

ok, what we’re going to do? I’m not a guru, so, lets find a guru and ask him or her. I would rather want to her, but… never mind. what ever. anonymouse
said: “well then you can try using the modified commandline plugin get the latest from my repositary (i think the downloads doesn’t hold the latest one) and use its childdbg function to debug the childs in succession you can also use windbg with its .childdbg command here is a log of a session tracing this with ollydbg

well, now we can debug children process as well, but… basically they’re the same. they execute the main loop and we want to trace only this loop. we’re not interested to trace start-up code every time. we want to set breakpoints, but… breakpoint affects only the parent process!!! not good. and this is the second point!

my solution is: to use hard-coded software breakpoints. just put breakpoint wherever you want with HIEW or other hex-editor (software breakpoint is just CCh byte) and load the program under your favorite debugger (IDA-Pro as an example). just do not forget to restore the original content under CCh code. for IDA-Pro and OllyDbg is easy to write a simple script/plug-in to automate the job.

ops!!! breakpoints in children processes cause crash! yes! coz they are not under debugger!!! who is supposed to catch the breakpoint expectations?! Soft-Ice of course!!! start Soft-Ice, type “I3HERE ON“, exit from Soft-Ice and run execlp.exe w/o debugger (Soft-Ice works in background).

wow!!! now we can debug children process _with_ breakpoints!!! now, our hacker’s life is a poem!!!

ok, another example (type it or download source and binary):

main(int c, char **v)
{ printf(“\rattach to me or kill me, my PID: %d”,
GetCurrentProcessId()); Sleep(33); execlp(v[0], v[0], 0, 0);}

try to attach to it or… kill the beast! just thinking :) the solution is simple. as the last resort press CTRL-Break, but… of course, the code might ignore it, so it’s just a loophole. real code will be not breakable by this simple trick.

 

# anti-attach: BaseThreadStartThunk => NO_ACCESS

another anti-attach trick. during attaching to the process, operation system creates a thread inside it and as far as we know, every thread has the start address. the address of the system thread is BaseThreadStartThunk. it calls BaseAttachComplete, who calls DbgBreakPoint in order to raise the breakpoint exception to pass control back to debugger. so, if we block BaseThreadStartThunk somehow, DbgBreakPoint will be never called and a debugger will never get control. theoretically…

…practically, operation system notifies a debugger when a new thread is about to be created, thus a debugger does not need in DbgBreakPoint at all!!! just set Option\Debugger option\Events\Break on new thread in Olly or Debug\Debugger options\Stop on thread start/exit in IDA-Pro and enjoy!!!

but, there is something else. first of all – these options are not set by default. second of all – if the system thread issues an exception – we can’t just continue execution! we need to kill the system thread to suppress the exception – not every hacker knows it and not every debugger allows us to do it (IDA-Pro does not).

well, guess, “Break on new thread” is set. this means our debugger stops _before_ executing the first command of BaseThreadStartThunk. how we’re going to generate an exception?! it’s easy! page of BaseThreadStartThunk => NO_ACCESS! of course, operation system will send exception notification to the debugger, allowing us to kill the system thread and continue executing/tracing the main one, but as it was said above not every hacker are ready to handle this situation.

ok, lets play with this trick. be warned: it’s not safe. we can’t set no access only for BaseThreadStartThunk, it affects the whole memory page where might be essential functions, but… for W2K/XP/S2K3 it works well. just… BaseThreadStartThunk is not an exported function. so, how we’re going to find where it’s located in memory? guess, the most universal way is to create a child process, attach to it, get CREATE_THREAD_DEBUG_EVENT notification and memorize u.CreateThread.lpStartAddress.

download the sources and binary of the POC to play with.

Olly fails to attach and the only way to continue debugging is to kill the system thread

Olly fails to attach and the only way to continue debugging is to kill the system thread

 

# Process Explorer – bloody hell of indefinite waiting bugs

long time ago I found a bug in Process Explorer pointing out that it uses wrong algorithm of retrieving Thread Start Address. all threads created with CreateRemoteThread has Thread Start Address pointing to KERNEL32.DLL. it’s true, but help- and sense-less. I sent my bug report to Mark, but got no answer and posted it on my old blog: “bug in Process Explorer (a gift for malware)

it means that Process Explorer is not reliable enough, we can’t trust it anymore and yesterday I found more bugs. they’re very common and almost _every_ application has numerous bugs like this. are you intrigued? well, lets begin!!!

download to_attach_ldr.exe (anti-attach trick, based on damaged PEB=>PPEB_LDR_DATA – read this post for more info), run it and… ask Process Explorer to display properties of “to_attach_ldr.ex” process (yeah! “ex”, not “exe” – another bug?!). now, go to “Threads” tab and…

ops!!! Process Explorer freezes falling into infinitive loop with 100% CPU load. ~60% is to_attach_ldr.exe and ~40% is CSRSS.EXE. ok, close to_attach_ldr.exe and Process Explorer immediately wakes up. this means it just was waiting the even that was not going to happen.

ok, another example. download to_attach_33.exe (anti-attach based on intercepted NtRequestWaitReplyPort, described here ). run it and ask Process Explorer to show properties, go to “Threads” tab and… you know what will happens in the next moment. freezing!!!

freezing Process Explorer

freezing Process Explorer

we just found out how buggy Process Explorer is. but why? what’s the issue? the answer: NT has numerous functions like WaitForSingleObject, WaitForDebugEvent, etc. they all take dwMilliseconds argument specifies time to wait for an event. if the parameter is INFINITE, the function does not return until an event has occurred. the problem is – almost every programmer uses INFINITE and does not handles time out error. admit, you did this too?

Ilfak does for sure and I pointed out it before (“another EnableTracing() bug“).

ok, we got two points. first – never use INFINITE unless you’re 100% sure it works. the second point: if malware creates a malicious thread inside a trusted application – anti-attach tricks help it to survive. many anti-viruses are unable to enumerate threads in this case and some of them just freezes. very effective DoS attack against pro-active protections!!!

note: I tested Process Explorer 11.4 under W2K SP4, not tested other versions yet, but guess the bug is there.

 

# NtRequestWaitReplyPort abuses IDA-Pro

good news first. my simple anti-anti-attaching plug-in is coming soon and it works very well. meanwhile, I’m experimenting with different anti-attaching technologies and wish to share a few new (old?) tricks with you.

well, the method based on NTDLL!DbgBreakPoint (see “try to attach to me: if you can!” ) is not good enough to hurt IDA-Pro. like Ilfak said – just set “Stop on debugging start” checkbox in the debugger options to stop IDA-Pro _before_ NTDLL!DbgBreakPoint. how it’s going to help?! nothing! but we will try. press F7 several times. go to Debug\Open subviews\Open threads. do you see two threads there? one is the main thread of the app, another – the system tread, created by DebugActiveProcess() API. the point is – we don’t need the system thread anymore. we should kill it. why? the debugged application might inject bad code into it. but IDA-Pro does not allow us to kill treats.

OllyDbg does. ok, run Olly, go to Options\Debugging options\Events\Break on new thread [x]. Attach to the to_attach_31.exe. ok, OllyDbg has been stopped. now, View\Threads. do you see two threads there? current thread is the system thread. kill it! (context menu\kill thread). um, the thread does not want to die. don’t worry it’s almost dead. now, click another thread (the main), context menu, actualize it and start tracing the main thread step-by-step or just press F9 to run. the system thread is disappeared. there was injected code displaying “shit happens”, but since the thread has been killed – no shit!!! everything is just fine!!!

this is universal technology. I tested it on large malware/protectors collection and it works well! at least for Olly. for IDA-Pro we need to write a script or plug-in, killing unwanted threads.

ok, forget about NTDLL!DbgBreakPoint. back to IDA-Pro. “Stop on debugging start” is set, IDA-Pro attaches to the process (any process you want) and stops. where it stops? let me see…

NTDLL!77F88B6C ZwRequestWaitReplyPort proc near
NTDLL!77F88B6C mov eax, 0B0h ; NtRequestWaitReplyPort
NTDLL!77F88B71 lea edx, [esp+arg_0]
NTDLL!77F88B75 int 2Eh
NTDLL!77F88B77 retn 0Ch ; << here
NTDLL!77F88B77 ZwRequestWaitReplyPort endp

so, IDA-Pro stops at NTDLL!77F88B77, when NtRequestWaitReplyPort NTCALL has been executed, so NtRequestWaitReplyPort (called by CsrClientCallServer) is executed _before_ stop. thus, if we intercept NtRequestWaitReplyPort – it will be easy for us to abuse IDA-Pro or do something unexpected. and IDA-Pro has nothing to do this it.

the problem is: NtRequestWaitReplyPort is very popular function and it’s used not only by debugger. so, we can’t just intercept it. we have to check the caller – the thread ID.

for example:

mov eax, fs:[18h] ; // *TIB
mov eax, [eax+24h] ; // CurrentThreadId
sub eax, [our_tid] ; // ?another Thread
jz to_old ; // => no dbg

; // perform stack overflow
die: push eax
jmp die

; // all ok, passing control to the old func
to_old: jmp ds:[old_NtRequestWaitReplyPort]

I wrote a simple POC, abusing IDA-Pro and OllyDbg. download it, run exe. do you see message – “attach to me”? well, ask Olly to attach. Olly attaches without any problems, but… the string changes to “debugger is detected” and the process is still running. wow!!! of course, we can stop the process and continue tracing, but… the point is – the debugger has been detected. how? I just injected my code into NtRequestWaitReplyPort to set global flag if we’re under debugger. the main thread checks this flag and changes its behavior if we’re under debugger. of course, in this simple case we can fix it after attaching, but imagine what happens if the injected code will wipe out all code of the app or destroy the critical structures or just free a few memory blocks cause random crashes?

OllyDbg stops too late. our code injected into NtRequestWaitReplyPort executes before, and debugger has no control under it. what’s about IDA-Pro? try to attach to to_attach_33.exe (all check box in debug options are set). what do we see? the protection tell us “debugger is detected”, the process is running, but IDA-Pro… freezes. what she is waiting for? and how to save our database? we don’t want to kill IDA-Pro, don’t we? right! kill to_attach_33.exe with Process Explorer. IDA-Pro will return from dead to alive.

IDA-Pro 5.3 fails to attach

IDA-Pro 5.3 fails to attach

well, who will break this simple crack me? who will find the way how to attach to the process do not disturbing the protection?

 

# attach to me… if you can (part II)

the previous post describes how to intercept attaching, but that way does not prevent attaching itself. as it happens there is a simple and elegant way to block any attaching attempts. just wipe out PEB=>PPEB_LDR_DATA field. the application is running well, the process is present in the processes list of Task Manager/Process Explore, but… it’s not listed in the Olly 1.10/Olly 2.00i attach windows!!!

to_attach_ldr.exe is not present in the attach windows!

to_attach_ldr.exe is not present in the attach windows!

ok, guys another plan! load the file directly into OllyDbg 1.10 in order to debug it. can we debug it? well, yes, but… no. OllyDbg 1.10 does not show us the module list (so, how we’re supposed to set breakpoints on API?) and the map window is empty as well. OllyDbg 2.00i and IDA-Pro 5.3 have no such problem.

IDA-Pro 5.3 can’t attach to the process as well, she just freezes!!! and there is nothing to do but terminate IDA-Pro with all changes we have made. a very nasty bug!

the source code is extreme simple. see it bellow or download.

__asm{
mov eax, fs:[30h] ; // PEB
mov [eax + 0xC], eax ; // damage LdrData to prevent attaching
}
// do something
while(1) printf(“\rattach to me [%c]“,x[++a % (sizeof(x)-1)]), Sleep(100);
}

so, you get it. any ideas how to hack it? does anybody know the way how to attach to the process?

note: Elias Bachaalany checked IDA-Pro 5.4 (both with WinDbg plug-in and build-in win32 debugger). it does not freeze, but attached is code crashed inside NTDLL.DLL and IDA catches a lot of exceptions, so this trick works for IDA-Pro 5.4 as well. it’s not IDA-Pro bug! and IDA-Pro has nothing to do to fix it.

 

# self-overwritten REP STOS/MOVS, IDA-Pro 5.4 and Ko

once upon a time was MS-DOS and ancient debuggers like Turbo-Debugger, Soft-Ice and many others. and there were anti-debug tricks. one of them was based on self-overwritten REP STOS/MOVS instruction. it worked great against all existing debuggers, including CUP 386 (exe unpacker with build-in CPU emulator).

I used this tricks for years. I would almost forget about if Silviocesare not posted “Anti-debugging prefetch tricks and single stepping through a rep stos/movs” article on his blog (very nice blog, btw).

I was interested: what’s about modern debuggers? what’s about emulators like BOCHS? what’s about IDA-Pro 5.4 with BOCHS-based debugger? imagine, how surprised I was when I found out that IDA-Pro 5.3, Olly 1.10 and Soft-Ice not only can be detected this way, but also lost the control during step over tracing! debugged code just escapes out of the debugger!!! IDA-Pro 5.4 with BOCHS module fails to emulate the self-overwritten REP STOS/MOVS instruction (so it can be detected as well) and lost control on Step Over tracing. only Olly 2.00i recognizes attempts to espace and blocks them, however it can be detected the same way.

for testing reasons I wrote a simple program with self-overwritten REP STOSB command (see source bellow).

std
xor ebx, ebx
mov al, 43h ; // INC EBX
mov edi, offset end_of
mov ecx, 6
REP STOSB
NOP
NOP
NOP
end_of: NOP
cld

download it, load into IDA-Pro 5.3 and start tracing REP STOSB instruction (F7 hot key). what do we see? REP STOSB changes NOP to INC EBX, overwrites four commands and overwrites itself (STOSB). since, during tracing CPU generates a single step exception every iteration, REP STOSB becomes REP INC EBX and as far as we all know, REP works only with string commands, so REP INC EBX is not executed and REP loop finishes with ECX = 1.

now, run the program without tracing. CPU pipelines REP STOSB and executes it until ECX > 0. REP STOSB modifies only data cache, while the instruction is executed on the pipeline and CPU does not recognizes modification of the code, so REP loop finishes with ECX = 0.

Olly 1.10/200i and Soft-Ice also fails to trace self-overwritten REP STOSB instruction. of course, if we trace the program with our hands, it’s easy to set a breakpoint _after_ it and run the code without tracing, but!!! many plug-ins use trace engine for their needs, so the trace engine should work fine and it’s possible to fix debuggers – just before executing REP STOS/MOVS we have to perform some checks and if the command overwrites itself we either set a breakpoint either emulate CPU behavior.

ok, run the program under BOCHS (IDA-Pro 5.4 support a special plug-in, allowing us to debug code on the fly). regardless of whether we trace program or not, the REP loop finishes with ECX = 1. well-known x86-emu plug-in gives us the same result, and this result is definitely wrong.

by the way, did I hear a question: how long CPU is executing overwritten REP STOS/MOVS command? there is no universal answer. it depends on CPU internal behavior and external evens like interrupts. when an interrupt is generated, CPU stops executing overwritten REP STOS/MOVS. a good way to create a pseudo-random generator! I’m going to write about it in the next post.

meanwhile, some CPU have a bug. they executes CLD commands _before_ overwritten REP STOS/MOVS will be stopped or finishes. as result, REP STOS/MOVS changes the direction and hits the memory not supposed to be written. I’m investigating this case now, will publish the result soon.

well, let’s return to our muttons. load the program into IDA-Pro 5.3/5.4 and perform Step Over tracing. move cursor to REP STOSB, press F8 and… the debugger lost the control!!! why? the answer is: to gain control back after REP STOSB command IDA-Pro sets a software breakpoint on the next command. we all know that a software breakpoint it’s just INT 03 (CCh) instruction and in our case this instruction is overwritten by REP STOSB. thus the breakpoint is wiped out and the process is executed until another breakpoint will be triggered. if there is no other breakpoints – the debugged code escapes out of the debugger!

what’s about Olly 1.10 and Soft-Ice?! fast check shows us like they do not lost the control and stop after REP STOSB. but… how they do it? well, they just use hardware breakpoints!!! and if all four hardware breakpoints are in use, the debuggers set a software breakpoint like IDA-Pro does, so they lost control as well. not good!

Olly 2.00i (didn’t check other versions) is the only debugger who is able to detect that the breakpoint was wiped out. if it happens we have a warning message. impressive! Olly 2.00 is a great debugger doubtless!!!