Archive for the ‘anti-dbg’ 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?!


# 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 loc_401007:
.code:0000000000401007 nop
.code:0000000000401008 xor [eax+ecx], cl
.code:000000000040100C loc_40100C:
.code:000000000040100C lea rax, loc_401013
.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 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


# die Vista, die or why DEADDEEF is alive?

intraarterial injection: fixing old bugs in Vista ms-guys inevitably add new ones. don’t ask me for proofs unless you want to hurt your face-painting wretched system. do you know the system I’m talking about? good! the following code has no impact on NT, W2K, XP, but… it freezes malformed Vista. it just hangs the system up! (I tested Vista SP0). download the binary or compile the file by yourself.


get off the subject: remember a simple anti-dbg trick with closing a non-existing handler? something like CloseHandle(0xBADC0DE) or CloseHandle(0xBADC0DE). if we’re under a debugger – OS generates C0000008h (INVALID HANDLE) exception. no debugger means no exception. the problem is: how to close an assuredly invalid handler? if you didn’t open it, any system DLL might opened it. of course, you can use GetHandleInformation() to check: if the handler has been opened, but… it’s too obvious (for hackers) and too trivial to be interested for us. there is another way — our way.

flowing well: has it never come in upon your mind how OS assigns handlers? a handler is DWORD, right? but it’s impossible to get all values busy. some values will be taken, but some of them should be free, because it’s impossible to open all of 4,294,967,296 possible handlers. it’s out of the limit! so, lets perform a fast research of system internals. what we’re going to do is: to consume all handlers until CreateFile() says: “no more handlers, I give up“. well, time to call GetHandleInformation() and check: is there any predictable template? which handlers are taken and which are not?

dead marines: holly cow!!! just look at it!!! wow! this is the very template we looked for! handlers 0h .. 02h are taken, handler 07h is taken as well, but… the rest of them fits the following equation: (((h – 0×12) % 04). so, it’s easy to determine handlers that will be not taken whatever happens to them, thus these handlers will definitely raise an exception on the close attempt. the point is: closing a handler like 1Bh looks reasonable from hacker’ point of view, but it’s just a way to generate an exception under debugger.

HANDLE: 00h is invalid
HANDLE: 01h is invalid
HANDLE: 02h is invalid
HANDLE: 03h is valid
HANDLE: 04h is valid
HANDLE: 05h is valid
HANDLE: 06h is valid
HANDLE: 07h is invalid
HANDLE: 08h is valid
HANDLE: 09h is valid
HANDLE: 0Ah is valid
HANDLE: 0Bh is valid
HANDLE: 0Ch is valid
HANDLE: 0Dh is valid
HANDLE: 0Eh is valid
HANDLE: 0Fh is valid
HANDLE: 10h is valid
HANDLE: 11h is valid
HANDLE: 12h is valid
HANDLE: 13h is invalid
HANDLE: 14h is valid
HANDLE: 15h is valid
HANDLE: 16h is valid
HANDLE: 17h is invalid
HANDLE: 18h is valid
HANDLE: 19h is valid
HANDLE: 1Ah is valid
HANDLE: 1Bh is invalid
HANDLE: 1Ch is valid
HANDLE: 1Dh is valid
HANDLE: 1Eh is valid

Achilles’ spear: so, you got it! we have the magic formula allowing us to check any arbitrary value. take 0xBADC0DEh for example. download the sources of IsInvalid.c and call IsHandlerInvalid(0xBADC0DE) or simile run IsInvalid.exe. as you can see, 0xBADC0DE could not be taken, so it’s a good choice to cause an exception.

ok, another try — 0xDEADBEEF. just pass the value to our magic function and… ops! it says: “HANDLE: DEADBEEFh is possibly valid“, so it’s potentially unsafe to use CloseHanlde(0xDEADBEEF). oh, come on! fat chance to close a file, opened by system or custom DLL, but… it’s still possible. btw, VMProtect uses CloseHanle(0xBADC0DE), which is safe. coincidence? or… anyway, Dermatolog (Иван Пермяков, Екатеринбург –the geek who created it) is a very wise guy and his protector is one of the best. it’s stuffed by anti-dbg tricks and it was a pleasure for me to dig them up. what’s about you?

handler consuming leads to consume kernel memory as well (handler_explorer.exe is running), sorry for the Russian screen-shoot, will appreciate your help, if somebody send me eng one (info # re - lab . org )

handler consuming leads to consume kernel memory as well (handler_explorer.exe is running), sorry for the Russian screen-shoot, will appreciate your help, if somebody send me eng one (info # re - lab . org )


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

in a nutshell: IDA-Pro 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

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, 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 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, BOCHSDBG, unaligned pe, impact area

IDA-Pro, BOCHSDBG, unaligned pe, impact area


# JL/JGE Intel CPU bug as anti-reversing trick

months ago Bow Sineath (a very clever reverser!) asked me: “does JL [jump is less] instruction check ZF flag?” I said: “well, give me a second to think, well, it’s supposed to check it, otherwise it would act like JLE [jump if less or equal] and besides, JL is synonym of JNGE (jump if not great or equal), so JL should check ZF!“.

but, according to Intel’ manuals JL and JNGE check only if SF != OF. CMOVL/CMOVNGE work the same way. at that time I thought that it’s just a documentation bug and even pointed this out in my presentation on HITB 2008 conference.

fragment of Intel manual

fragment of Intel' manual

but I was wrong!!! I have checked it and found out that JL/JNGE does not check ZF flag!!! to do this I wrote extremely simple POC (if you’re too lazy to type, download source and binary):

mov eax, 002C2h ; S = 1, O = 0, Z = 1
push eax
jl jump_is_taken ; ==>
mov p, offset noo

mov eax, 2C2h/push eax/popfd set SF with ZF and clear OF. so, SF != OF, but ZF is set. what CPU is going to do? easy to check with Olly! just load the program and start tracing. ops!!! JL is taken!!! JL ignores ZF!!! x86emu (plug-in for IDA-Pro) acts the same. didn’t check other emulators yet.

well, it’s interesting. why JL (and similar commands) ignores ZF?! guess, normal CPU command (like TEST/CMP/XOR/etc) never set ZF if result is less, so JL just ignores it. but… if we set flags manually or use other tricks… it becomes a real trap!!! consider the listing above and ask your co-worker: is the jump taken or not? I’m sure, some of them will answer: of course, the jump is not going to be taken! a good anti-reversing trick!!! I just wonder – how software is still working on buggy hardware.

JL does not check ZF flag as it is supposed to do!!!

JL does not check ZF flag as it is supposed to do!!!


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


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