Archive for the ‘OllyDbg’ 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×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?!


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


# Olly Plug-ins and MS VC

oh, not again… I got so many letters “how to build Olly plug-ins with MS VC?“. so many too decide to answer here. (feel free to skip this post if you’re experienced enough). this is going to be step-by-step guide. and the first step is…

1) go to and download PDK 1.10
2) unpack it and see. there are Plugins.hlp (documentation, but who read documentation after all?), Plugin.h (include file with all definitions); Ollydbg.def (def file for linker), Bookmark.c/Cmdexec.c/Command.c – source code of a few simple plug-ins we’re going to build; cmdline.rtf – documentation for Cmdexec.c plug-in; there is also /VC50 folder. open it and see VC-related stuff: OLLYDBG.LIB – library file for linker, *.mak and *.ds? files for make and Visual Studio. but we’re going to build plug-ins with our hands, so… what do we need?!
3) we need: OLLYDBG.LIB, OLLYDBG.DEF and PLUGIN.H. this is all!
4) let’s try to build Bookmark.c from pure command line!
5) type: “CL.EXE /LD Bookmark.c Ollydbg.lib“, where /LD – key to make DLL (as we know plug-ins are DLLs), Bookmark.c – name of plug-in to build, Ollydbg.lib – library (it should be in current directory or any directory listed in “LIB” environment variable (type “SET LIB” to see your list of LIBs dir); PLUGIN.H should be located in the current directory (you can move it to any system include directory, just type “SET INCLUDE” to see the list);
6) ok, all system are go. we’re pressing enter, and… ops!!! PLUGIN.h wants us to specify /J key (to force compiler to use unsigned char, instead of signed char by default);
7) updated command line looks like: “CL.EXE /LD /J Bookmark.c Ollydbg.lib“, we’re pressing enter and…
8) …endless list of errors of 32 unresolved externals symbols. why?!
9) the answer is: OLLYDBG.LIB is incorrect!!! ok, we have DEF file, so no problem to create the new one;
10) “lib.exe /DEF:Ollydbg.def” (lib.exe comes with Microsoft Visual C++);
11) ok, we have a new Ollydbg.lib. lets try to build the source again… what?! the same errors!!!
12) well, DEF file is wrong and has to be fixed. open it with any text editor and replace all “_” by “”, save changes and exit (of course, we’re supposed to remove only “_” prefixes, do not touching “_” symbols in the middle of functions, but we’re lucky and there is no function with “_” in the middle);
13) run “lib.exe /DEF:Ollydbg.def” again;
14) try to build the source once more: “CL.EXE /LD /J Bookmark.c Ollydbg.lib
15) fatal error LNK1120: 8 unresolved externals
16) well, 8 is less than 32, so the progress is good and fixed .lib-file is working, but… something is still broken, but… look at names of the unresolved symbols!!!!
17) __imp__DefMDIChildProcA@16, __imp__MessageBoxA@16, __imp__CreatePopupMenu@0
18) they’re obliviously belong to USER32.lib! so, just add USER32.lib to our command line!!!
19) the final (we hope so) try look like: “cl.exe /J /DL Bookmark.c Ollydbg.lib USER32.lib
20) wow!!! it was built without any single error or warning!!! we’re very happy!!!
21) copy the fresh Bookmark.dll to Olly’ Plug-in directory and check how good (bad) it is!
22) btw, don’t forget about optimization!!! “cl.exe /Ox /J /DL Bookmark.c Ollydbg.lib USER32.lib“, where /Ox means – max. optimization (of course, feel free to use other compiler keys, whatever you want!!!)

you can download fixed version of Ollydbg.lib/Ollydbg.def. I tested it with Microsoft Visual Studio 6.0 and it works fine.


# Olly loads Olly to bypass anti-attach tricks /* Clerk’ trick */

the problem of anti-anti-attaching came up in conversation on the legendary site. Clerk (a very clever guy carring a heavy plasma gun, loaded with rounds of brilliant ideas) as always offered a very elegant, yet bizarre solution (ru). I wonder – what kind of Rasta stuff makes him so creative! well, stop to expatiate, back to business.

previous posts demonstrate numerous anti-attach tricks and most of them based on the system thread, creating by OS during attaching. here they are (the tricks): BaseThreadStartThunk => NO_ACCESS, NtRequestWaitReplyPort, DbgBreakPoint

the question is – how to ask OS do not create the system thread? to do it we should know OS internals. IDA-Pro/Soft-Ice shows us that KERNEL32!DebugActiveProcess comes to NTDLL!DbgUiDebugActiveProcess, who calls NTDLL!ZwDebugActiveProcess/ NTDLL!DbgUiIssueRemoteBreakin| NTDLL!DbgUiStopDebugging (just to dissemble NTDLL!DbgUiDebugActiveProcess to see it with your own eyes).

the point is – NTDLL!ZwDebugActiveProcess does all job, attaching a debugger to the process. . as soon as NTDLL!ZwDebugActiveProcess returns status ok, the process has been attached and can be debugger. but! operation system calls NTDLL!DbgUiIssueRemoteBreakin just to notify the debugger by generating breakpoint exception, however, we don’t need it!!!

so, what we’re going to do? I prefer to use old soft-ice with global breakpoints support. just set HW or software breakpoint on NTDLL!DbgUiDebugActiveProcess or NTDLL!ZwDebugActiveProcess and skip the rest of the function. it’s easy, but soft-ice does not work with newest operation system.

Clerk found the way how to do this with Olly. the idea is: load Olly into Olly. yeah! right!

1) load Olly into Olly /* to avoid a mess lets call the first Olly (I) and the loaded copy – Olly (II) */;
2) Olly (I): Set breakpoint on NTDLL!DbgUiDebugActiveProcess: View\Executable Modules\NTDLL.DLL, CTRL-N, “DbgUiDebugActiveProcess”, F2, ENTER;
3) Olly (I): run Olly (II): press F9 several times until right corner “paused” changed by “running” meaning that Olly (II) is still under debugging but it’s running now;
4) ALT-TAB to switch to Olly (II);
5) Olly (II): File\Attach\name_of_the_trickily_process to attach (for example: to_attach_36.exe);
6) Olly (I) pops up, the breakpoint has been triggered;
7) to_attach_36.exe is still running;
8) Olly (I): press F8 several time until NTDLL!ZwDebugActiveProcess is executed;
9) to_attach_36.exe has been stopped, Olly (II) has been attached to it, Olly (II) is stopped as well;
10) Olly (I): move cursor to the next command after NTDLL!DbgUiStopDebugging, right click to context menu and “new origin here” or simple press CTRL+Gray * (“gray” means small numeral keyboard);
11) Olly (I): press F9 to run Olly(II);
12) ALT-TAB to switch to Olly (II);
13) Olly (II) shows naked screen w/o any info, to_attach_36.exe is running;
14) Olly (II): View\Threads. do you see the only one thread? the main thread of the app?! wow!
15) Olly (II): press “pause” to stop to_attach_36.exe;
16) Olly (II) updates CPU window and from that moment we can trace to_attach_36.exe as usual;

well, you got it. a nice trick to bypass anti-attaches. it’s very powerful and universal, but does not work with PEB=>LdrData . um, every technique has its own limitations.

meanwhile, you probably know, if the process is already attached to another process, we can’t attach our debugger to it. many protections use this trick – they create a child process (packed), attaches to it for dynamic unpacking. but there is a loophole. we can attach to the parent process unless the child not attached to the father. yes!!! a debugged process can attach to the debugger!!! it looks like (parent <== attach ==> child)

I’ll write about it latter, showing you how to break this chain. for now, you can play with Clerk’s trick!

Olly loaded into Olly attached to to_attach_36.exe

Olly loaded into Olly attached to to_attach_36.exe


# 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


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

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

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

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


# try to attach to me… if you can!

why we might want to attach to active process? there are zillion reasons to do it. for example, the file is packed and stuffed with many adbg tricks. or, maybe, we found a suspicious process in memory and want to analyze it. maybe something else…

there many ways to prevent attaching: self-replicated and self-debugged processes do it very well, but there is another way. please, download the crack-me (with sources) and try to handle it by yourself.

  • 1) run to_attach_31.exe;
  • 2) run OllyDbg or IDA-Pro;
  • 3) try to attach the debugger to the process;
  • 4.1) in Olly: File => Attach => to_attach_31.exe;
  • 4.2) in IDA: Debug => Attach to process => to_attach_31.exe;
  • 5) see “shit happens” messages;
  • 6) the process is still running and the debugger has no control;
Olly is unable to attach to the process

Olly is unable to attach to the process

well, how it worked? when debugger is attaching to process, a new thread is created. NTDLL!DbgBreakPoint function is called and it’s called by not-exported KERNEL32!_BaseAttachComplete@4. the problem is that the thread is created inside the debugged process, so the debugged process can change NTDLL!DbgBreakPoint. for example, intercept it and terminate the system thread preventing attaching. or… abuse the debugger! why not?! we can do almost everything, including creating a faked thread and attaching the debugger to it!
see the source code.

p = (DWORD) GetProcAddress(LoadLibrary(“NTDLL.DLL”), “DbgBreakPoint”);

// nasty dirty trick – we just overwrite the code of DbgBreakPoint
VirtualProtect(p, 1024, PAGE_EXECUTE_READWRITE, &old);
jmp inject
x_code: mov eax, offset souriz
jmp eax
inject: mov esi, offset x_code
mov edi, p
mov ecx, 2

the code above patches NTDLL!DbgBreakPoint, injecting mov eax, offset souriz/jmp eax code over it. not good! but it’s just a POC after all, so feel free to improve it. anyway it woks!

I tested it under: W2K SP4, XP SP3, S2K3 SP1. please, test the crack-me under other systems. a few people reported that MsgBox, called by souriz() function not appears on the screen. it’s strange. I have no idea why – need more info to find out.

the last question is: how to bypass this trick? I think, the best strategy – just to check NTDLL/KERNEL32 before attaching (via ReadProcessMemory) and restore them if it’s necessary, but… it’s possible to prevent attaching, changing only data and the second problem: in real life we want to know what the program changed exactly. will think how to handle it.

P.S. see comments for more details.


# Baghdad – dead alive breakpoints

not Baghdad actually, just Borland stuff. it’s russian jargon. borland => baghdad (they sound quite similar). well, you want to hack a Baghdad program? and breakpoints do not help you to hack it fast? well, guys…

set breakpoints on library functions. IDA-Pro recognizes them and once they have been recognized and addresses determined – feel free to use any debugger – Olly or Soft-Ice.

the most interested functions are listed bellow (of course, the list is incomplete, just gives you an idea what to do):

@TControl@GetText$qqrv ; TControl::GetText(void)
@System@@LStrCmp$qqrv ; System::__linkproc__ LStrCmp(void)
@Sysutils@Now$qqrv ; Sysutils::Now(void)
@Sysutils@DecodeTime$qqr16System@TDateTimerust2t2t2 ;; Sysutils::DecodeTime(System::TDateTime,ushort &,ushort &,ushort &,ushort &)
@Sysutils@StrToInt$qqrx17System@AnsiString ; Sysutils::StrToInt(System::AnsiString)
@Controls@TControl@SetVisible$qqro ; Controls::TControl::SetVisible(bool)
@Controls@TControl@SetText$qqrx17System@AnsiString ; Controls::TControl::SetText(System::AnsiString)
@Mask@TCustomMaskEdit@GetText$qqrv ; Mask::TCustomMaskEdit::GetText(void)

btw, there is a good plugin for Olly – GoDup (by godfather+) allowing to use IDA-Pro signatures directly.