All Blog Entries

  1. Weird export forwarding thanks to Vista x64 SP1

    After installing the SP1 for Vista x64, I noticed that ImpREC stopped working properly on some files using DefWindowProcA and DefWindowProcW from user32.dll.
    These 2 APIs are forwarded as usual respectively to NtdllDefWindowProc_A and NtdllDefWindowProc_W from ntdll.dll but cannot be "unforwarded" back to user32.dll using the traditional method.

    I'll explain how the loader usually resolves forwarded exports, the unforwarding method used by ImpREC and why it fails on those 2 particular cases.

    Using the information provided by the Import Directory of the executable, the loader looks for a matching name or ordinal in the specified dll.
    After a match is found, the corresponding entry from the AddressOfFunctions array is retrieved from the Export Directory and augmented by the ImageBase of the dll.
    That value is then written to the IAT.

    Sometimes, for compatibility reasons, an import can be forwarded to another one from a different module.
    In that case, the AddressOfFunctions entry does not lead to code but to an ASCII string composed of the module name and the import name or ordinal.
    Code:
    .text:7DCA751E ; LRESULT __stdcall DefWindowProcA(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam)
    .text:7DCA751E DefWindowProcA  db 'NTDLL.NtdllDefWindowProc_A',0
    .text:7DCA7539 ; Exported entry 151. DefWindowProcW
    .text:7DCA7539                 public DefWindowProcW
    .text:7DCA7539 ; LRESULT __stdcall DefWindowProcW(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam)
    .text:7DCA7539 DefWindowProcW  db 'NTDLL.NtdllDefWindowProc_W',0
    The loader then restarts the whole process from the beginning, using the info from the forwarding string rather than the original info from the Import Directory of the executable.
    The Entry Point of the newly-found function is written to the IAT instead.

    ImpREC finds the IAT and goes through it to identify all the imports that it contains.
    Some entries belong to ntdll.dll and need to be "unforwarded" to their original location.
    DefWindowProcA should be unforwarded from NtdllDefWindowProc_A.


    http://img510.imageshack.us/my.php?image=presp1zr0.png

    If everything goes well, the original import is found by "bruteforcing" the Entry Point of every function until a forwarding string is found: NTDLL.DefWindowProc_A at the Entry Point of DefWindowProcA in user32.dll and then comes in some guesswork.

    Because an import could have been forwarded from another module, doesn't mean that it really was, there are some false-positives.
    The guesswork is based on a very crude probability analysis based on the module name of the previous import and the module name of the next import.
    EndDialog from user32.dll is almost never forwarded from shlwapi32.dll.

    Something changed with Vista x64 SP1 through some modifications of wow64.dll since the content of the \SysWOW64 directory should be the same as the standard Vista 32-bit SP1.
    Some hotfix is applied only during run-time by WoW64.


    http://img177.imageshack.us/my.php?image=postsp11vz2.png


    http://img177.imageshack.us/my.php?image=postsp12vf6.png

    During execution, the AddressOfFunctions entries of DefWindowProcA and DefWindowProcW from user32.dll are modified.
    The RVA based at the ImageBase becomes greater than the SizeOfImage and leads into the memory area of ntdll.dll rather than the usual forwarding string.
    Instead of 0x0001751E, the AddressOfFunctions becomes 0x015C3D42 or 0x01793D42 or 0x01B83D42 for DefWindowProcA.

    The same result is achieved but this method prevents the unforwarding of some imports through the traditional method since there is no forwarding string anymore.
    It leads into code now:
    Code:
    ntdll.dll:77C43D42 ntdll_NtdllDefWindowProc_A:
    ntdll.dll:77C43D42 jmp     ds:off_77CB6020
    ...
    ntdll.dll:77CB6020 off_77CB6020 dd offset loc_7669C0E7     ; DATA XREF: ntdll.dll:ntdll_NtdllDefWindowProc_Ar
    And jumps back to user32.dll:
    Code:
    user32.dll:7669C0E7 loc_7669C0E7:                           ; DATA XREF: ntdll.dll:off_77CB6020o
    user32.dll:7669C0E7 push    10h
    user32.dll:7669C0E9 push    offset unk_7669C158
    user32.dll:7669C0EE call    near ptr unk_766BC240
    user32.dll:7669C0F3 call    near ptr unk_766980D7
    ...
    Unforwarding is still possible anyway since a side-effect could be identified: the Entry Point of both imports become identical.
    GetProcAddress(DefWindowProcA) == GetProcAddress(NtdllDefWindowProc_A)
    GetProcAddress(DefWindowProcW) == GetProcAddress(NtdllDefWindowProc_W)

    To sum everything up:
    It doesn't really matter, the average user of Vista x64 SP1 would never notice the difference.
    Unpacking in a 32-bit VM instead is still more reliable than under WoW64.

    This will be a part of my proposed upcoming ReCon talk.
    Categories
    Uncategorized
  2. Process Memory Dumper for Credentials Disclosure Vulns

    Hi,

    This last period was full of intersting findings, I've published two advisoryes on Bugtraq:

    http://www.securityfocus.com/bid/28420

    and

    http://www.securityfocus.com/archive/1/490265/30/0/threaded

    So I also coded a Process Memory Dumper, useful to improve these vulns.
    It can be downloaded here:
    http://evilcry.altervista.org/other/ProcessMemoryDumper.zip

    Enjoy!

    See you to the next post..
    Categories
    (In)Security
  3. (Part 2 of .NET native exe insights)Serial fishing and patching .NET exes with Ollydb

    (Part 2 of .NET native exe insights)Serial fishing and patching .NET exes with Ollydbg.


    Last blog post I pointed out how native exes, when used improperly, do nothing to deter reverse engineer of
    completely decompiling your product, and doing with it as they please (cracking). Now, I would like to assume
    that the developer bothered reading my blog post, and actually bothered wiping the IL from his native exe. While
    I do admit that this is a "final" solution to decompilation, as I mentioned before it is faaaar from a "final"
    solution to crackers. Hackers have been going at native code for years, so with a bit of brainpower and Olly, a
    native .NET exe should pose no challenge to them.

    In this post I will observe a simple keygenme, and I will show you how I was able to
    a) patch it
    b) fish a serial for it...

    in less that 5 minutes with Olly.

    Here is the link to the keygenme we will be dealing with(same as in last blog post):

    http://www.filesend.net/download.php?f=644ee1dfd1b9246aee11d64b931bd0fb

    Download it, extract it anywhere, and Ngen it

    >ngen unpackme.exe.

    Then, take unpackme.exe, and load it into Olly. Check all exceptions, and run the Unpackme. It will pop up with
    a little dialogue asking for a name and serial. Click the "Check" button, and observe the error message:

    "Invalid serial. Pls don't hack me :'("

    Hardy harr.

    Well, now lets think for a second. This is a string that is needed for the unpackme to run. Therefore, it can
    probably be found the native image of the unpackme. We also know that all strings in a .NET exe are stored in
    the metadata. As I pointed out in the last tutorial, the metadata of a .NET exe is in the .IL section of the
    native exe. So, we know that somewhere in the .IL section of our native exe, we will find a string saying:
    "Invalid serial. Pls don't hack me :'("

    Furthermore, if you paid close attention to the .NET file format, you know that all strings in .NET are stored as
    unicode. So, somewhere in the .IL section of our native .NET exe there will be a UNICODE string that says:
    "Invalid serial. Pls don't hack me :'(".

    Now, suppose that we locate this string. What do we do with it? Quite simple: We put a hardware breakpoint upon
    it. Once it is accessed, we know that the routine it was accessed from is part of the serial checking routine.

    Alright, now in Olly, with the unpackme running in the background, press ALT+M to open a list of all modules.
    Scroll down a bit until you find the native image of unpackme.exe (Unpackme.ni.exe). You should see this:

    Code:
    30000000    00001000 (  Unpack_1 3             PE header     Imag   R         RWE
    30002000    00004000 (  Unpack_1 3  .text      code          Imag   R E       RWE
    30006000    00001000 (  Unpack_1 3  .extrel    code          Imag   R E       RWE
    30008000    00005000 (  Unpack_1 3  .data      code,data     Imag   RW        RWE
    3000E000    00001000 (  Unpack_1 3  .xdata                   Imag   RWE       RWE
    30010000    00001000 (  Unpack_1 3  .dbgmap                  Imag   R         RWE
    30012000    00004000 (  Unpack_1 3  .il                      Imag   R         RWE
    30016000    00001000 (  Unpack_1 3  .rsrc      resources     Imag   R         RWE
    30018000    00001000 (  Unpack_1 3  .reloc     relocations   Imag   R         RWE
    Now, we are interested in the .IL section of this native exe, because that is where the string we are trying to
    breakpoint is. In the dump window of Ollydbg, press CTRL+G, type 30012000, and press enter. This will move the
    Ollydbg hex dump window to the beginning of the .IL section. Then, still in the dump window, press
    CTRL+B (binary search), and under unicode type in:
    "Invalid serial.". Then press enter to let Olly search. It should end up here:

    Code:
    300142FD   49 00 6E 00 76 00 61 00  I.n.v.a.
    30014305   6C 00 69 00 64 00 20 00  l.i.d. .
    3001430D   53 00 65 00 72 00 69 00  S.e.r.i.
    30014315   61 00 6C 00 2E 00 20 00  a.l... .
    3001431D   50 00 6C 00 73 00 20 00  P.l.s. .
    30014325   64 00 6F 00 6E 00 27 00  d.o.n.'.
    3001432D   74 00 20 00 68 00 61 00  t. .h.a.
    30014335   63 00 6B 00 20 00 6D 00  c.k. .m.
    3001433D   65 00 20 00 3A 00 27 00  e. .:.'.
    30014345   28 00 01 81 7B 54 00 68  (.{T.h
    3001434D   00 65 00 20 00 70 00 6F  .e. .p.o
    30014355   00 69 00 6E 00 74 00 20  .i.n.t.
    3001435D   00 6F 00 66 00 20 00 74  .o.f. .t
    30014365   00 68 00 69 00 73 00 20  .h.i.s.
    3001436D   00 55 00 6E 00 70 00 61  .U.n.p.a
    30014375   00 63 00 6B 00 6D 00 65  .c.k.m.e
    3001437D   00 20 00 69 00 73 00 20  . .i.s.
    30014385   00 66 00 6F 00 72 00 20  .f.o.r.
    Cool! This is the badboy string we are interested in. Write down the address, restart the target in Olly, and
    press F9 to run Olly once again. Do not click on the check button yet. First, go to the address we wrote down
    (300142FD) select the first 4 bytes,
    Right click -> breakpoint -> hardware, on access -> byte

    Now, go back to the unpackme, and click on the "Check" button. Olly should break with a hardware DWORD on access
    at a place that looks like this:

    Code:
    7814507A    F3:A5              REP MOVS DWORD PTR ES:[EDI],DWORD PTR DS:[ESI]
    7814507C    FF2495 94511478    JMP DWORD PTR DS:[EDX*4+78145194]
    78145083    90                 NOP
    Alright now, go to
    Debug -> hardware breakpoints

    in Olly, and delete your hardware breakpoint that you set upon this string.

    Now, its time to trace a bit with F8 until we get to the .text section of Unpackme.exe. Just hold F8 until
    you end up here:

    Code:
    300041D0    57                 PUSH EDI
    300041D1    56                 PUSH ESI
    300041D2    53                 PUSH EBX
    300041D3    55                 PUSH EBP
    300041D4    83EC 10            SUB ESP,10
    300041D7    891424             MOV DWORD PTR SS:[ESP],EDX
    300041DA    8BF1               MOV ESI,ECX
    300041DC    8B05 0CE00030      MOV EAX,DWORD PTR DS:[3000E00C]                 ; Unpack_1.300081B4
    300041E2    8338 00            CMP DWORD PTR DS:[EAX],0
    300041E5    74 05              JE SHORT Unpack_1.300041EC
    300041E7    E8 12E1084A        CALL mscorwks.7A0922FE
    After you've debugged .NET exe's a bit in Olly you will recognize this as the beginning of a method, just like
    PUSH EBP
    MOV EBP, ESP

    usually marks the beginning of a routine in VC++...

    Anyways, since this routine has accessed the "Invalid serial" string, we can assume that this routine is the
    serial check routine. Start tracing at it with F8. A messagebox telling you you entered the wrong serial will
    pop up after you trace over this call:

    Code:
    300042A6    8B05 18BF0030      MOV EAX,DWORD PTR DS:[3000BF18]
    300042AC    8B08               MOV ECX,DWORD PTR DS:[EAX]
    300042AE    FF15 C0BF0030      CALL DWORD PTR DS:[3000BFC0]                    ; System_W.7B26EC88
    300042B4    90                 NOP
    Interesting... look around in Olly and try to get a feel for what is happening. Even a noob should be able to
    understand what is happening here:

    Code:
    30004270    8BF8               MOV EDI,EAX
    30004272    6A 00              PUSH 0
    30004274    8BD3               MOV EDX,EBX
    30004276    8BCF               MOV ECX,EDI
    30004278    FF15 BCBF0030      CALL DWORD PTR DS:[3000BFBC]                    ; Compare strings (Microsoft.VisualBasic.dll)
    3000427E    8BF8               MOV EDI,EAX
    30004280    85FF               TEST EDI,EDI
    30004282    0F94C0             SETE AL
    30004285    0FB6C0             MOVZX EAX,AL
    30004288    894424 04          MOV DWORD PTR SS:[ESP+4],EAX
    3000428C    837C24 04 00       CMP DWORD PTR SS:[ESP+4],0			; were they the same?
    30004291    74 12              JE SHORT Unpack_1.300042A5			; if not, JMP
    30004293    8B05 14BF0030      MOV EAX,DWORD PTR DS:[3000BF14]
    30004299    8B08               MOV ECX,DWORD PTR DS:[EAX]
    3000429B    FF15 C0BF0030      CALL DWORD PTR DS:[3000BFC0]                    ; good boy message. 
    300042A1    90                 NOP
    300042A2    90                 NOP
    300042A3    EB 10              JMP SHORT Unpack_1.300042B5
    300042A5    90                 NOP
    300042A6    8B05 18BF0030      MOV EAX,DWORD PTR DS:[3000BF18]
    300042AC    8B08               MOV ECX,DWORD PTR DS:[EAX]
    300042AE    FF15 C0BF0030      CALL DWORD PTR DS:[3000BFC0]                    ; bad boy message.
    300042B4    90                 NOP
    300042B5    90                 NOP
    300042B6    90                 NOP
    300042B7    90                 NOP
    300042B8    83C4 10            ADD ESP,10
    300042BB    5D                 POP EBP
    300042BC    5B                 POP EBX
    300042BD    5E                 POP ESI
    300042BE    5F                 POP EDI
    300042BF    C2 0400            RETN 4
    Simple, eh? Just for kicks, nop the JE at 30004291 and press F9 to run the unpackme. Click on the "Check" button and watch ...

    Updated March 24th, 2008 at 02:00 by rendari

    Categories
    Uncategorized
  4. Rebuilding native .NET exes into managed .NET exes by Exploiting lefotver IL...

    In the last article I wrote about native exe's, I briefly touched upon the issue of IL code being
    left over in generated Native EXE's, and how this could be a possible security hole that hackers could
    exploit when trying to reverse your .NET app. How big of a hole is this, you might ask? Very big. I
    managed to fully rebuild my old managed .NET exe just from the native image provided by Ngen. I aim
    to explain the steps I took in this blog post.

    First things first, we will be using this .NET exe for out experimentations:
    http://www.filesend.net/download.php?f=644ee1dfd1b9246aee11d64b931bd0fb

    It's just a simple Unpackme I wrote and submitted to crackmes.de. If you suspect malicous code, feel
    free to decompile it in Reflector.

    Anyways, extract the exe anywhere, and execute Ngen upon it

    Code:
    H:\temp>ngen unpackme.exe
    Microsoft (R) CLR Native Image Generator - Version 2.0.50727.42
    Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
    Installing assembly H:\temp\unpackme.exe
    Compiling 1 assembly:
        Compiling assembly H:\temp\unpackme.exe ...
    UnpackMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null <debug>
    
    H:\temp>
    Then browse to your Global Assembly Cache at H:\WINDOWS\assembly\NativeImages_v2.0.50727_32\UnpackMe,
    find UnpackMe.ni.exe, and copy it over to some temporary location, where we can "work" on it.

    Now, the interesting thing about Ngen is that it does not eliminate the IL or the metadata, because
    while the IL code is not needed for execution, the metadata is, because all the strings and other
    relevant data that the program needs are contained within the metadata. So, Ngen copies all the
    metadata to the .IL section of the native exe, and copies the IL code as an afterthought (I assume
    for debugging purposes). Anyways, the point is that native exe's generated with Ngen have the
    IL code and metadata still in them, so a wily hacker should be able to use them to rebuild a managed
    exe similar to the original exe before Ngen had its way with it. The hacker can then load this
    managed exe into Reflector to decompile it, and steal your code or crack it with ease.

    NOTE: managed code = bytecode (decompilable)
    unmanaged code = native code (I wish we could decompile that =( )

    This is a major issue because all protectors that boast converting IL code to native code to protect
    your programs all use Ngen, so if the protectors forget to remove the IL you (the reverser) can just
    reconstruct the original exe and then have fun with it =)

    Anyways, so you have a copy of UnpackMe.ni.exe. This is what you would get after a "native" protector
    converted your IL code into native code. So, UnpackMe.ni.exe is all a reverser trying to reverse this
    target would have availible to him.

    Now, let us proceed to convert UnpackMe.ni.exe into a decompilable exe =).

    Load UnpackMe.ni.exe into CFF explorer, and browse around a bit. You will see that the exe is not
    a valid win32 exe (no entrypoint) and that there appears to be next to no metadata (No Methods metadata
    table or any of that other good stuff...). Seems like we have our work cut out for us.

    In hindsight: no, not really.

    First things first: we want to have valid metadata. Thankfuly, with CFF explorer this is easy to
    achieve since Daniel Pistelli (the author) documented the native header of .NET exe's enough for us
    so that we don't have to use a hex editor to find the IL code/metadata anymore (btw, thanks Daniel
    for this neat lil tool =) )

    In CFF Explorer, go to a little tab on the left market "Native header". You will see that the "Native
    Header" is mostly populated with unknown RVA's and sizes. However, there are 4 DWORD's that are of interest
    to us. They are:
    Original metadata RVA - 0x00012000
    Original metadata size - 0x00002BC0
    Original MSIL code RVA - 0x00014D30
    Original MSIL Code Size - 0x00000DBF

    Ok, write down these values somewhere. Now, go to the tab in the left of CFF Explorer marked ".NET directory",
    and replace the values "Metadata RVA" and "Metadata Size" with the "Original metadata RVA" and
    "Original metadata size" values that we got from the native header. Also change the Flags dword from
    00000004 (IL Library) to 00000004 (IL only). Cool, now click on the "Tables" tab, so that we can browse the
    metadata tables that now became availible to us.

    The "Method" tables are of particular interest to us, because these are the ones that tell us where the IL code
    is. So, click on the "Method" tables to open the list. There are 56 Methods btw. Note that, since we will need
    that later on. Now, click on the first Method you see. In this case, it is cctor. CFF Explorer will then display
    all the interesting things about the "cctor" method. If you look at the method RVA, you will see that it is
    00000004. That's way too low. So, what is wrong here? Well, that RVA is actually the displacement from the
    "Original MSIL code RVA" value in the Native header. So, to get the "real" RVA is actually:

    cctor RVA + Original MSIL code RVA = Real RVA.

    Our next step, therefore is to replace all the RVA's in these tables with their "Real RVA's", so that reflector
    and ILDasm may load them. I wrote a primitive little CFF explorer script for this. Here it is:

    Code:
    -- this functions checks if a flag is set
    function IsFlag(value, flag)
        if (value & flag) == flag then
            return true
        end
        return false
    end
    
    -- --------------------------------------------------
    -- the main code starts here
    -- --------------------------------------------------
    
    filename = GetOpenFile("Open...",  "All\n*.*\nexe\n*.exe\ndll\n*.dll\n")
    
    
    if filename == null then
        return
    end
    
    pehandle = OpenFile(filename)
    
    if pehandle == null then
        return
    end
    
    -- get dotNet Directory offset if any
    
    dotnetoffset = GetOffset(pehandle, PE_DotNETDirectory)
    
    
    -----------------------------------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------------------------
    
    MethodRVA = 0x0000D406
    MethodCounter = 0
    OrigMSILRVA = 0x00014D30
    NumberOfMethod = 56
    junkDWORD = 0
    
    
    
    while MethodCounter < NumberOfMethod do
    
        junkDWORD = ReadDword(pehandle, MethodRVA)
        junkDWORD = junkDWORD + OrigMSILRVA
        WriteDword(pehandle, MethodRVA, junkDWORD)
        MethodRVA = MethodRVA + 0x0E
        MethodCounter = MethodCounter + 1      
    
    
    end
    
    
    
    
    -----------------------------------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------------------------
    
        filename = GetSaveFile("Save As...",  "All\n*.*\nexe\n*.exe\ndll\n*.dll\n")
    
        if filename == null then
            MsgBox("Couldn't save file", "fast dotnet fix", MB_ICONEXCLAMATION)
        else
            if SaveFileAs(pehandle, filename) == true then
                MsgBox("File successfully saved.", "fast dotnet fix", MB_ICONINFORMATION)
            else
                MsgBox("Couldn't save file", "fast dotnet fix", MB_ICONEXCLAMATION)
            end
        end
    
    return
    NOTE: If you are working on an executable other than the one I provided, fill in
    MethodRVA
    OrigMSILRVA
    NumberOfMethod
    with the appropriate values from the exe you are working on.

    NOTE: MethodRVA = the RVA of the first Method table entry in the metadata. In this case, the offset of
    where the Method table for the "cctor" method starts.

    Take the above script, and copy paste it into a new file called *anything*.cff. Then double click on the
    script to get CFF explorer to execute it, select "Unpackme.ni.exe" to be processed, and save the processed
    file as "fixing1.exe". Remember to save the changes we have done to Unpackme.ni.exe before executing this
    script on it.

    Now, close Unpackme.ni.exe and open fixing1.exe ...
    Categories
    Uncategorized
  5. Some Quick Insights Into Native .NET exe's (part 1 of?)

    So, what are natively compiled .NET exes? Well, to answer that question we have
    to go back to how the .NET runtime works.

    All your VB.NET and C# code is translated during compilation from the language
    in question to MSIL (Microsoft Intermediate Language). This is a sort of stack
    based assembler variant that, in combination with metadata present in the executable,
    can be translated back into high level code (VB.net and C#). This is why tools
    such as reflector and dotDecompile exist on the .NET platform; the same effect
    is much harder to achieve with native code.

    Basically, the new possibilities for decompilation introduced in the .NET
    architecture have caused a lot of companies to shit themselves. Intellectual
    property (IP) is the lifeblood of the company. If someone can rip the idea and
    or source out of your product, and implement it in theirs, there is very little
    you can do to prevent them. This is becoming a major issue in the .NET dev circles
    (along with the fact that decompilation = easier cracking for malicous reverse
    engineers bent upon pirating goods to disrupt the global economy and plunge the
    world into deep recession).

    So, .NET devs are a lot more willing to invest time and money in securing their
    products. Frankly, given how shitty 99% of the "security" products on the market
    are, they're wasting their time.

    One of the security products that in my opinion falls into the "not well thought
    out" category is anything that boasts security through native code. Look at it this
    way: hackers have been cracking native code for how long? 2 decades? 3 decades?
    What makes you think that all of a sudden, in the grand year of 2008, they will
    start having problems hacking native code? Maybe it will be even EASIER for them
    because they no longer have to adapt to the foreign .NET architecture, but now
    simply have to load the exe into Olly and go at it the "old fashioned way".

    So, back to the question at hand. What are natively compiled .NET exes? Basically,
    they are exe's containing platform specific code that has been produced by the JIT
    instead of the aforementioned MSIL code. This makes it impossible to decompile the
    .NET code the old fashioned way (with Reflector).

    Producing .NET exes isn't really that simple. To natively compile a .NET exe into a
    native exe, you must use ngen.exe (comes with the SDK). Ngen is a native code
    generator provided by M$, and it's purpose is to increase performance. An application
    that demands performance might use Ngen to compile itself during installation.

    The newly produced native executables are not runnable. In fact, they are not even
    valid Win32 applications. They may be located in the Global Assembly Cache (GAC) of
    the local machine where Ngen was executed. If you do not know what the GAC is, read
    up on it here:

    Demystifying the .NET Global Assembly Cache
    By Jeremiah Talkar
    http://www.codeproject.com/KB/dotnet/demystifygac.aspx

    Now, I guess you're anxious to see the native exes I was just talking about. Desafortunadamente,
    it is not possible for you to access the GAC with Windows explorer right away. Thankfuly,
    a quick registry fix from the article quoted above will lets us browse the GAC from
    Windows Explorer. I quote:

    "If you want to disable the Assembly Cache Viewer and see the GAC in all its naked glory
    within Windows Explorer, you can set HKLM\Software\Microsoft\Fusion\DisableCacheViewer [DWORD] to 1."

    Simple, eh? Now, take any exe .NET exe (for example helloworld.exe) and execute Ngen upon it:


    C:\Windows\system32>cd C:\temp

    C:\temp>ngen HelloWorld.exe
    Microsoft (R) CLR Native Image Generator - Version 2.0.50727.1433
    Copyright (c) Microsoft Corporation. All rights reserved.
    Installing assembly C:\temp\HelloWorld.exe
    Compiling assembly C:\temp\HelloWorld.exe ...
    HelloWorld, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null <debug>

    C:\temp>pause
    Press any key to continue . . .

    There, we Ngen'd HelloWorld.exe. Now, whenever we execute HelloWorld.exe, the JIT will load
    the native HelloWorld.exe from the GAC and execute it, instead of compiling the IL in the
    HelloWorld.exe we are double clicking on. Like I said, this is intended to improve performance.

    To find the native compiled HelloWorld.exe on our hard drive, browse to

    C:\Windows\assembly\NativeImages_v2.0.50727_32\HelloWorld\355240658e5a51e36767993bef4ed510\
    ^
    This is different on each computer.

    You should see one file, and that is: HelloWorld.ni.exe. As I mentioned before, it is this file
    that is loaded as a module when the JIT executes.

    As you can see by double clicking on HelloWorld.ni.exe, it is not a valid image. This means that
    you cannot distribute it. That is one of the downfalls of Ngen.exe. You must have a valid exe
    with MSIL in it to generate an Ngen image. You cannot simply distribute the Ngen'd image as it
    is invalid.

    Salamander .NET Protector changes all this. This is one of the protectors that takes a somewhat
    amusing approach towards solving the problem of invalid Ngen'd images. I took a quick look at it
    by downloading the Scribble Demo from their homepage:
    (no reversing involved, reversing is illegal you know :P )

    http://www.remotesoft.com/linker/intro.html

    Just look at the file paths in the link above:

    \scribble-native\mdeployed\C\WINDOWS\assembly\NativeImages_v2.0.50727_32\Scribble\eccb67b11447c9488a7a35bab51a a59b

    It will become quite obvious that all its doing is
    emulating the GAC. It has its own GAC in there, with all the components scribble (native compiled)
    needs. When you run scribble.exe, it initializes the .NET Jit and points it towards its own GAC. .NET
    then grabs everything it needs from there (including native compiled scribble(Scribble.ni.exe))), and executes it.

    Now that's just a hypothesis on how it works. Without real reversing I cannot verify my results.
    And since reversing it would be illegal, I guess I'll have to pass up the opportunity this time :P

    Now, how secure is salamander .net protector? Well, I guess compared to MSIL code native code is 10x more secure, but
    does that mean that its really SECURE? Not necessarily.

    First of all, there is a small bug in the protector where it makes it preserve the IL code from the original exe. Ntoskrnl
    described it in his article that he did on salamander .net protector. You can find it here:

    http://www.pmode.net/USERS/116/Files/salamander.htm

    But lets just ignore the IL code in memory for now, and focus on attacking the native code. Remember that HelloWorld.exe from
    earlier in the chapter? Let's try Ngenning that, and then having some fun with it :>

    First off, we need both need to be looking at the same HelloWorld.exe. Here is the code that I used, just paste it into an
    empty VB.net project and compile. For button1 you can put any button, so long as it executes the code below
    BTW, for the purposes of this project I used VB.net express 2008

    Code:
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            MessageBox.Show("Greetings")
    
        End Sub
    End Class
    Simple piece of work, eh? Will just pop out a messagebox saying Greetings, and that's that. Compile it, run it, and then
    proceed to the next paragraph of this article.

    Ok now, first of all lets generate a valid native image for HelloWorld.exe. Just do:

    > ngen HelloWorld.exe

    Now go to the global assembly cache

    > cd C:\Windows\assembly\NativeImages_v2.0.50727_32\HelloWorld\355240658e5a51e36767993bef4ed510

    , find HelloWorld.ni.exe, and copy it to some temporary folder.

    Now do:

    > ngen uninstall HelloWorld

    I know this might not make sense to you, but just bear with me.

    Now, take Olly, and open the original HelloWorld.exe (the one which we execute ngen upon). Find the IL code in the hex view
    window (IL code is easy to recognize from a hex editor once you get used to looking at it; if you're having trouble finding
    it in the exe gets its RVA with CFF Explorer orjust search for 2A (2A is the bytecode for the IL_Ret instruction)). Here is
    how the beginning of the IL code looks for me from Olly:

    Code:
    00E221C0  13 30 02 00 3B 00 00 00  0.;...
    00E221C8  1B 00 00 11 00 7E 0D 00  ...~..
    00E221D0  00 04 14 28 58 00 00 0A  .(X...
    00E221D8  0C 08 2C 20 72 0B 01 00  ., r.
    00E221E0  70 D0 09 00 00 02 28 25  p...(%
    00E221E8  00 00 0A 6F 59 00 00 0A  ...oY...
    00E221F0  73 5A 00 00 0A 0B 07 80  sZ...
    00E221F8  0D 00 00 04 00 7E 0D 00  ....~..
    00E22200  00 04 0A 2B 00 06 2A 00  ..+.*.
    ...

    end of IL code:

    (scroll down)

    Code:
    00E22A10  00 00 04 02 7B 0C 00 00  ..{...
    00E22A18  04 14 FE 01 16 FE 01 0B  
    00E22A20  07 2C 0D 02
    ...
    Categories
    Uncategorized
  6. Symbol Type Viewer 32Bit/64Bit v1.0.0.3

    Today I've finded a great tool, Symbol Type Viewer 32Bit/64Bit

    Symbol Type Viewer is a tool which makes it possible to easily
    visualize the types which can be defined in the symbols of the modules of the
    systems Microsoft Windows 32/64bit. Moreover, it makes it possible to convert
    these informations for the C language (.h) and the disassembler IDA of DataRescue
    (.idc).
    Link here

    Have a nice Day,
    Evilcry
    Categories
    Uncategorized
  7. gee mail patented algorithm

    i was reading the mails from older to newer
    and here is what happens when i finish off mail no 96-51
    51- 50 of 50 hurrah
    Categories
    Uncategorized
    Attached Thumbnails Attached Images  
  8. Microsoft's Rich Signature (undocumented)

    In the last days I've been quite sick, so I decided that as long as I had to stay in bed I might at least use the time to do something useful (or quite so). What happened is that someone asked what the Rich Signature was. It might seems strange but in all these years I didn't even notice it, I just overlooked it as part of the dos stub (incredible but true). Unable to answer, I noticed together with this person that the subject was completely undocumented. It might not even be much important, but you might find it an interesting reading after all.

    http://ntcore.com/Files/richsign.htm

    Since information about this topic is non-existent, the reader might not know what I'm talking about:

    00000070 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 00 mode....$.......
    00000080 E7 B3 9D E7 A3 D2 F3 B4 A3 D2 F3 B4 A3 D2 F3 B4 糝
    00000090 60 DD AC B4 A8 D2 F3 B4 60 DD AE B4 BE D2 F3 B4 `ݬ`ݮ
    000000A0 A3 D2 F2 B4 F8 D0 F3 B4 84 14 8E B4 BA D2 F3 B4 
    000000B0 84 14 9E B4 3A D2 F3 B4 84 14 9D B4 3F D2 F3 B4 :?
    000000C0 84 14 81 B4 B3 D2 F3 B4 84 14 8F B4 A2 D2 F3 B4 
    000000D0 84 14 8B B4 A2 D2 F3 B4 52 69 63 68 A3 D2 F3 B4 Rich
    000000E0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
    000000F0 00 00 00 00 00 00 00 00 50 45 00 00 4C 01 04 00 ........PE..L.

    The data between the dos stub and the PE Header. It ends with the word Rich. It is produced by microsoft VC++ compilers only and it is encrypted.

    To dELTA who has been hunting me down for this article for more than a week: I hope you're satisfied now! Damn swedish bloodhound! =)

    Updated March 4th, 2008 at 21:15 by Daniel Pistelli

    Categories
    Uncategorized
  9. Reverse Engineering the flash virtual machine

    Hi,

    i recently started a small project where i try to obfuscate a small flash sample. i'm especially interested in the virtual machine and the interpreted bytecode. after some googling i found two interesting papers from adobe itself. i was pretty suprised to see that adobe provides such a good documentation about the virtual machine and its bytecode.

    you can take a look at the pdfs here:

    http://www.adobe.com/devnet/actionscript/articles/avm2overview.pdf

    and

    SWF and FLV File Format Specification - http://www.adobe.com/licensing/developer/

    For the last document you will need to step through the license process of adobe. but dont be shy they offer a free license for a year, then you must refresh your license to use the pdf.

    probably this information is wide spread but i think it will be interesting for a few people.

    most of the obfuscator out there i saw for flash are rather crapy, i think there should be better ways to protect a swf application.

    Regards,

    OHPen

    Updated February 25th, 2008 at 09:07 by OHPen

    Categories
    The incredible world of virtual machines and byte code
  10. Collaborative RCE Tool Library (CRCETL) site update

    During the last week I've applied a bunch of additions and smaller bug fixes to the Collaborative RCE Tool Library site.

    If you notice any problems, please let me know!

    Here is a summary of the (externally) more notable updates:

    • Added the field "Related URLs" to all tool entries. These URLs are meant to contain other URLs in addition to the main homepage for the tool, which can be useful when using the tool, e.g. an online manual, a third-party tutorial, a useful forum discussion thread, an informative blog entry etc.
    • Added a "Most Recent Updates" page (linked from the menu under the category navigation tree to the left), which lists all recently added or updated tools in the library (mostly for RSS-impaired users, since the RSS feeds are a much more efficient way of keeping up to date about all new and updated RCE tools).
    • Added a "Full Library Index" page (linked from the menu under the category navigation tree to the left), which lists links to all tools in the entire library, for easy manual searching through all tool names.
    • Made the listings of tools on category pages recursive, for easier, more intuitive and more efficient navigation.
    • Made the category tool counters in the category navigation tree recursive, for easier overview and improved correctness.
    • Added reporting of parent categories for all tool entries in the addition/update RSS feeds.
    • Added multi-select for the category selection option when adding or updating tools.
    • Created a better favicon.
    • Fixed a bug that caused invalid sorting in the category navigation tree, all categories in the tree are now strictly alphabetically sorted.
    • Fixed a bug that caused the "parent category markers" (auto expansion and red selection for all parent categories of the current category or tool) in the category navigation tree, now it should work 100%.
    • Fixed some bugs related to double HTML encoding.


    Enjoy!
    Categories
    Uncategorized
  11. Two Extensions added into Collaborative RCE

    Hi,

    Just a reminder, today I've added two OllyDbg Extensions into Collaborative RCE Tool Library:

    http://www.woodmann.com/collaborative/tools/index.php/OllyHeapTrace

    and

    http://www.woodmann.com/collaborative/tools/index.php/OllyCallTrace

    Two great plugins that surely will help people intersted in Vulnerability Research

    Regards!
    Categories
    TechLife
  12. SoftICE Installation.

    Recently ive spent a lot of time installing SoftICE on various machines and i want to post
    all the various problems i came accross and ones i have solved.

    DriverSuite v3.2
    ----------------

    XPSP2/Win2kSP4

    first of all before installing softice you should install the default driver version
    of your graphic card, this means the original driver that came with the machine or
    the earliest version you can find, both ATI and NVIDIA offer a back catalogue of their
    previous driver versions.

    Keep the INIT string to a basic x; before you have softice working
    Disable mouse support, no real reverser needs a mouse in softice ;-)
    Make sure you install DirectX
    Use the Detect and Test buttons in the video section of setup.

    Issues
    ------

    1) ".. A device attached to the system is not functioning .. "

    I have solved this problem many times by ..

    1.) Installing a different graphic driver.
    2.) Disabling SPTD.SYS from the registry
    HKEY_LOC_MACHINE/system/services/currentcontrolset/SPTD/Start change to 4

    2) Upon starting softice the window flashes by then a system freeze occurs.

    I have solved this problem only a "few" times by ..

    1.) In winice.dat place the string NTSYMBOLS=ON, use the symbol loader to grab symbols for
    kernel32.dll user32.dll ntoskrnl.exe hal.dll gdi.ll convert and load these.

    If this doesnt work then

    2.) replace the osinfo.dat and osinfob.dat in system32\drivers with new ones from the
    compuware ftp, you can google for links.

    If this doesnt work, try undo option 1

    The above works for me frequently, however on non freshly installed systems conflicts can
    occur with other software. If you really want softice to work then you are going to have
    to spend time disabling software, AntiVirus/Spyware is a good start, and not just disabling
    them but uninstalling any software which may install a kernel mode driver with system hooks
    to identify the problem, However i recommend a freshly installed machine dedicated for
    kernel mode debugging.

    Once up and running you can use my pretty INIT line

    INIT="lines 60;ws 5;wc 25;wd 6;set font 2;color 03 4e 4e 1b 1b;x;"


    VMWARE
    ------

    after installing XPSP2 you must install vmware tools, then save and shutdown the machine,
    next you must edit the .vmx file and place in the following lines

    vmmouse.present = FALSE
    svga.forceTraces = "TRUE"


    I invite people to add comments to help build an informative thread on softice problems,
    please try and structure your reply in a clear way, such as,
    Problem: x Solution: x

    /yates.
    Categories
    Uncategorized
  13. Eeye BinDiffing Trick

    Hi,

    Around here exist truly intersting tools for Binary Diffing, useful for Vulnerability Research and or Malware Analysis.

    The two most famous tools are:

    • Sabre Security BinDiffv2
    • Eeye Binary Diffing Suite (EBDS)


    The eEye Binary Diffing Suite (EBDS) is a free and open source set of utilities for performing automated binary differential analysis, but has a little problem, seems to be explicitly developed for IDA 5.0, and no other IDAs versions are supported.

    But there is a trick to avoid that an make it working with all IDAs Versions.

    Open with Regedit the following RegKey:

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\IDA Pro_is1

    And change the Key Entry DisplayName with the string IDA Pro Standard v5.0 or IDA Pro Professional v5.0

    and..

    Happy Diffing

    See you to the next post..
    Categories
    TechLife
  14. Idc script and stack frame variables length

    Among all the precious information retrieved by Ida theres something I always use when I need to study a target: stack frame. Its quite useful when you want to see the list of parameters and local variables, but it would be great to see the size of each item. Yes, you can get the length but you have to calculate it each time. I sometimes need this kind of information, especially when I have to deal with fixed length buffers. I tried inspecting through some Idas menu without luck, its strange that Ida doesnt provide such information so I decided to write a little idc script able to retrieve local *big* buffers. (If theres an Ida hidden feature please tell me)
    I wanted to attach the original script I wrote here, but I think its much more useful to explain some details about the functions I used leaving the script to you as an exercize. In this simple example Ill show you how to find out the length of each item inside a stack frame. Lets start with a simple function:


    The stack frame created by Ida is divided into some parts, it looks like a sequence of fields:
    - local variables
    - saved registers
    - return address
    - function parameters

    Looking at the picture above is pretty easy to locate local variables (ObjectAttributes, KeyValueInformationLength, ResultLength) and function parameters (Handle, ValueName). Moreover you can guess the length of each item. According to the four parts I mentioned above there are some more items that are not specified by Ida, Im referring to saved registers and return address. If you look at the offset of each item youll surely find out something odd. Look at the gap between ResultLength and Handle: 00C bytes. 4 bytes are reserved for ResultLength variable, but there are 8 unreferenced bytes. Its time to take a look at the stack frame window (ctrl-k):


    Here is the answer. Ida uses two special fields named r and s, the length of each field is 4 bytes. They are the return address and the saved registers.

    Ok, how to get the size of the items using an idc script? As you can see from the picture the stack frame looks like a structure definition, the idea is to read each item in sequence.
    Code:
    #include <idc.idc>
    
    static main()
    {
       auto id, i, firstM, lastM, address;
       auto mName, mSize, mFlag;
       
       address = 000013C92;        //    Address of the function to check
       id = GetFrame(address);
       firstM = GetFirstMember(id);
       lastM = GetLastMember(id);
       
       for(i=firstM;i<=lastM;i++)
       {
          mName = GetMemberName(id,i);   // Get the name
          mSize = GetMemberSize(id, i);  // Get the size (in byte)
          mFlag = GetMemberFlag(id, i);  // Get the flag
          Message(\n%s   %d   %x, mName, mSize, mFlag);
       }
    }
    First of all I need to get the function frame structure. I use GetFrame, it returns the id of the function frame structure. Its the first information to retrieve because you need the id when youll have to deal with the internal fields of the structure. Once you have the id you can start scanning the entire structure from the first till the last item. GetFirstMember and GetLastMember functions give you the first and the last offset. At this point you can retrieve all the information you need, in this example I get name, size and flag value from every item. The functions I used are GetMemberName, GetMemberSize and GetMemberFlag; pretty intuitive and easy to use. An output line will look like:
    Code:
    ObjectAttributes   24   60000400
    where name=ObjectAttributes, size=24 and flag=60000400. Which kind of information are hidden inside the flag value? idc.idc file contains all the necessary definitions:
    Code:
    #define FF_DATA 0x00000400L             // Data ?
    #define FF_STRU 060000000L             // Struct ?
    The field contains data and its a structure (OBJECT_ATTRIBUTES). And, what about Handle field?
    Code:
    Handle   4   25500400
    Browsing idc.idc file youll get:
    Code:
    #define FF_DATA  0x00000400L            // Data ?
    #define FF_0OFF  000500000L            // Offset?
    #define FF_1OFF  005000000L            // Offset?
    #define FF_DWRD  020000000L            // dword
    Ok, theres only a little behaviour to fix inside the script. Run the script and youll see some repeated lines, heres a snippet taken from the output:
    Code:
     
    ObjectAttributes   24   60000400
    ObjectAttributes   24   60000400
    ObjectAttributes   24   60000400
    KeyValueInformationLength   4   20000400
    KeyValueInformationLength   4   20000400
    KeyValueInformationLength   4   20000400
    KeyValueInformationLength   4   20000400
    ResultLength   4   20000400
    ResultLength   4   20000400
    ResultLength   4   20000400
    
    Ida repeats the field information on every byte of the field itself. To display only one item per field you can update the i variable inside the for statement, add the next line after the Message instruction:
    Code:
    i = i + GetMemberSize(id, i) - 1;
    The example ends here. It works almost fine, but it goes into an infinite loop with certain functions. From what Ive seen the problem occours when Ida is not able to understand which kind of variable has been declared. Look at this simple example:
    Code:
    ...
    INIT:BF9B0786 var_1A4         = dword ptr -1A4h
    INIT:BF9B0786 var_18E         = byte ptr -18Eh
    INIT:BF9B0786 var_4           = dword ptr -4
    
    var_18E is marked as byte but theres a big gap between var_18E and var_4. Stack frame windows reveals an interesting thing:
    Code:
    -0000018E var_18E         db ?
    -0000018D                 db ? ; undefined
    -0000018C                 db ? ; undefined
    -0000018B                 db ? ; undefined
    -0000018A                 db ? ; undefined
    -00000189                 db ? ; undefined
    -00000188                 db ? ; undefined
    -00000187                 db ? ; undefined
    -00000186                 db ? ; undefined
    -00000185                 db ? ; undefined
    -00000184                 db ? ; undefined
    -00000183                 db ? ; undefined
    var_18E length is 394 byte and as you can see Ida doesnt collapse the definition into a single line, but it explodes the variable through the 394 bytes.
    How can you solve this problem? You can use my initial script adding some more checks. Nothing hard of course, you have all the necessary functions, just use your brain defining a good algo. Hint: take a look at the value returned by GetMemberSize.


    Once you have a working script you can extend it covering all the declared functions and filtering the information youll get.

    Good luck and let me know if you are not able to solve this exercize!!!
    Categories
    Uncategorized
  15. dr7.gd on mp systems running sice

    SoftICE uses drX to perform step over. One interesting question is how does it do that on MP system? It could happen that thread is running at one CPU, but code which is executed in certain procedure could switch to different CPU, and still SoftICE manages to stepover correctly. How is that possible? Using IPI, of course.

    The best example is this code if steped over in SoftICE:

    Code:
            KeSetAffinityThread(cur_thread, 1<<0);
            KeSetAffinityThread(cur_thread, 1<<1);
    both calls will be steped over correctly, and that's because SoftICE sends IPI with Shorthand = All excluding self set in ICR to set drXes on both CPUs.

    I also wrote earlier that softice changes NMI handler from TaskGate to IdtGate on single cpu machine, but when I viewed IDT on MP system from SoftICE, it used TaskGate to hook NMI. So there are certain rules which have to be followed when drX access occurs from NMI and TaskGate.

    Handler must NOT iret if access to drX occurs from NMI, because iret will unblock NMI. Handler also must not use DbgPrint, or anything else that can trigger iret when executing from NMI...

    Also if we are in NMI, SoftIce won't clear NT flag in eflags, so any iret will lead to previous task. We can avoid this problem by clearing NT flag, but again, we unblock NMI using iret, so this is sidenote, not a real problem.

    This problem with iret is solved easily, by changing the way we return from int1 when it's caused from NMI:

    Code:
       
    __s0:           str     ax              ;get task register
                    cmp     ax, 58h         ;check if it is NMI
                    je      __nmi
                    
                    pop     es              ;not NMI so exit normally
                    pop     ds
                    pop     fs
                    popad                                   
                    iretd                                   
                                            
    __nmi:          mov     eax, [esp.regEflags]            
                    push    eax             ;NMI!! - restore eflags                
                    popfd                                   
                    pop     es              ;r0 epilog
                    pop     ds
                    pop     fs
                    popad
                    retn    8               ;ret to interupted code and
                                            ;clear cs/eflags stored on 
                                            ;stack...
    Bingo... dr7.GD is now working in mp system running sice
    Categories
    Uncategorized