Sunday, April 4, 2010

Anti-Emulation Through Syscalls

Long time no see, I know.
I was, and still am, very busy, which doesn't allow me to take care of the blog as much as I'd like.

Anyway, I was having a look at a bunch of packed malware and ran into a pretty cool anti-emulation trick. It's, in fact, already known and well documented but still, that's a nice one.
Those samples are packed with something that Kaspersky calls PE_Crypt.pnh (or PE_Patch.pnh for those with a patched EP).

This anti-emulation code is always put a few instructions after the EP. The first technique is really trivial to spot as it's just a bunch of MMX instructions that not all emulators support.
The second one is trickier.







Depending on the debugger you're using, if you step through this code, you're likely to get an access violation exception.
Setting a breakpoint after the interrupt call and running the debuggee should work just fine but you're likely to be surprised when checking registers values...

Indeed, when the interrupt returns, the edx register contains the value of eip. And this is exactly what this piece of code relies on to proceed with decryption.
Because of the fact that emulators often can't handle MMX instructions, special behaviors of interrupts, etc..., the interrupt will be ignored (or worse, emulation will fail) and edx will keep its value. This will lead to a crash since edx doesn't contain the right virtual address.

Question is, why does edx contain the same value as eip when the interrupt returns?
No mystery here, it comes from sysenter / sysexit.
Indeed, when having a look at the Intel instruction set reference doc, you can read the following about sysexit:
 The SYSEXIT instruction sets the following registers according to values specified by the oper-
ating system in certain model-specific or general purpose registers.

CS register       set to the sum of (16 plus the value in SYSENTER_CS_MSR)
EIP register      set to the value contained in the EDX register
SS register       set to the sum of (24 plus the value in SYSENTER_CS_MSR)
ESP register      set to the value contained in the ECX register
This is it, the address to jump to when the processor switches back to ring3 is saved into edx.

Easy to implement, but very efficient when it comes to avoid emulation and then detection by AV products.

1 comments:

  1. salut,
    blog sympa... Je l'ai ajouté dans ma blogoliste. Si le mien te convient d'ailleurs: http://infond.blogspot.com
    PS: stp, ne valide pas ce commentaire :)
    ++
    t0ka7a

    ReplyDelete