All Blog Entries

  1. Native Blocks Pre-Alpha

    Hello, I wanted to show you my new tool. I called it Native Blocks. It's a re-assembler basically. Since a written presentation would take me too much time I prepared a video presentation.

    http://www.youtube.com/watch?v=pDlwStN3KZY
    http://www.youtube.com/watch?v=ene6hvE5qVQ

    Again, this is a pre-alpha. This tool will soon support other technologies such as java, actionscript and maybe even x86. Right now it only supports .NET (and even .NET support will be hugely improved, like for instance supporting the direct modification of assemblies without having to use Rebel.NET).

    The development of this tool depends mainly on the interest of people.

    As I can be considered a student from now on, I would like to earn some extra money by writing tools such as this one. I have still my job as consultant, but it's a very limited partime, because I just became a student.

    This tool is in my opinion pretty good, it is not only good for deobfuscation purposes but also patching and assembling on the fly.

    If this tool can be sold, then the support of technologies will depend on requests. I think I'll add Java immediately and after that maybe x86/x64. Again it depends.

    Suggestions and comments are welcome.

    Updated July 3rd, 2009 at 16:36 by Daniel Pistelli

    Categories
    Uncategorized
  2. EventPair Reversing, EventPairHandle as Anti-Dbg Trick

    Hello,

    Here my little paper on EventPairs, and EventPairHandle as Anti-Dbg Trick

    http://evilcry.netsons.org/tuts/EventPairsHandle.pdf

    Have a nice read,
    Giuseppe 'Evilcry' Bonfa'
  3. RtlQueryProcessHeapInformation as Anti-Dbg Trick

    Hi,

    Directly derived from the previous Anti-Dbg Trick

    http://evilcodecave.wordpress.com/2009/04/14/rtlqueryprocessheapinformation-as-anti-dbg-trick/

    Have a nice read,
    Giuseppe 'Evilcry' Bonfa'
    Categories
    Uncategorized
  4. RtlQueryProcessDebugInformation as Anti-Dbg Trick

    The following paper will uncover some interesting undocumented functions relative to Windows Heap Enumeration.

    RtlCreateQueryDebugBuffer
    RtlQueryProcessDebugInformation
    RtlDestroyQueryDebugBuffer


    Here the prototypes for each function:

    Code:
    PDEBUG_BUFFER
    NTAPI
    RtlCreateQueryDebugBuffer(
    IN ULONG  Size,
    IN BOOLEAN  EventPair);
    Code:
    NTSTATUS
    NTAPI
    RtlQueryProcessDebugInformation(
    IN ULONG  ProcessId,
    IN ULONG  DebugInfoClassMask,
    IN OUT PDEBUG_BUFFER  DebugBuffer);

    Code:
    NTSTATUS
    NTAPI
    RtlDestroyQueryDebugBuffer(
    IN PDEBUG_BUFFER  DebugBuffer);
    Code:
    RtlCreateQueryDebugBuffer
    allocates buffer for storing heap data in case of success, it returns pointer to allocated debug buffer. Here the declaration of debug buffer:

    Code:
    typedef struct _DEBUG_BUFFER {
    HANDLE  SectionHandle;
    PVOID  SectionBase;
    PVOID  RemoteSectionBase;
    ULONG  SectionBaseDelta;
    HANDLE  EventPairHandle;
    ULONG  Unknown[2];
    HANDLE  RemoteThreadHandle;
    ULONG  InfoClassMask;
    ULONG  SizeOfInfo;
    ULONG  AllocatedSize;
    ULONG  SectionSize;
    PVOID  ModuleInformation;
    PVOID  BackTraceInformation;
    PVOID  HeapInformation;
    PVOID  LockInformation;
    PVOID  Reserved[8];
    } DEBUG_BUFFER, *PDEBUG_BUFFER;
    After the buffer allocation we can call the Heap Process Debug Information, we can call RtlQueryProcessDebugInformation to load all heap blocks of the process. This function loads entire heap nodes and corresponding heap blocks of the process. Debug Buffer contains the pointer to heap information structure at offset 0×38. First parameter of this heap structure is node count and after that it contains array of DEBUG_HEAP_INFORMATION structure which represent each heap node.

    Code:
    typedef struct _DEBUG_HEAP_INFORMATION
    {
    ULONG Base; // 0×00
    ULONG Flags; // 0×04
    USHORT Granularity; // 0×08
    USHORT Unknown; // 0×0A
    ULONG Allocated; // 0×0C
    ULONG Committed; // 0×10
    ULONG TagCount; // 0×14
    ULONG BlockCount; // 0×18
    ULONG Reserved[7]; // 0×1C
    PVOID Tags; // 0×38
    PVOID Blocks; // 0×3C Heap block pointer for this node.
    } DEBUG_HEAP_INFORMATION, *PDEBUG_HEAP_INFORMATION;
    As you should know a debugged process presents different flags respect a not debugged one, here the sample anti-dbg code:

    Code:
    #define WIN32_LEAN_AND_MEAN
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <Psapi.h>
    #include “defs.h”
    
    #pragma comment(lib,”ntdll.lib”)
    #pragma comment(lib,”psapi.lib”)
    
    void QueryDbgBufferMethod(void)
    {
    PDEBUG_BUFFER buffer;
    NTSTATUS ntStatus;
    
    buffer = RtlCreateQueryDebugBuffer(0,FALSE);
    
    ntStatus = RtlQueryProcessDebugInformation(GetCurrentProcessId(),
    PDI_HEAPS|PDI_HEAP_BLOCKS,
    buffer);
    
    PDEBUG_HEAP_INFORMATION heapInfo = PDEBUG_HEAP_INFORMATION(PULONG(buffer->HeapInformation) + 1);
    
    if (heapInfo->Flags == 0×50000062)
    MessageBoxA(NULL,”Debugged”,”Warning”,MB_OK);
    else
    MessageBoxA(NULL,”Not Debugged”,”Warning”,MB_OK);
    
    RtlDestroyQueryDebugBuffer(buffer);
    }
    and here ‘defs.h

    Code:
    typedef LONG NTSTATUS;
    #define STATUS_SUCCESS ((NTSTATUS)0×00000000L)
    
    typedef struct _DEBUG_BUFFER {
    HANDLE SectionHandle;
    PVOID  SectionBase;
    PVOID  RemoteSectionBase;
    ULONG  SectionBaseDelta;
    HANDLE  EventPairHandle;
    ULONG  Unknown[2];
    HANDLE  RemoteThreadHandle;
    ULONG  InfoClassMask;
    ULONG  SizeOfInfo;
    ULONG  AllocatedSize;
    ULONG  SectionSize;
    PVOID  ModuleInformation;
    PVOID  BackTraceInformation;
    PVOID  HeapInformation;
    PVOID  LockInformation;
    PVOID  Reserved[8];
    } DEBUG_BUFFER, *PDEBUG_BUFFER;
    
    typedef struct _DEBUG_HEAP_INFORMATION
    {
    ULONG Base; // 0×00
    ULONG Flags; // 0×04
    USHORT Granularity; // 0×08
    USHORT Unknown; // 0×0A
    ULONG Allocated; // 0×0C
    ULONG Committed; // 0×10
    ULONG TagCount; // 0×14
    ULONG BlockCount; // 0×18
    ULONG Reserved[7]; // 0×1C
    PVOID Tags; // 0×38
    PVOID Blocks; // 0×3C
    } DEBUG_HEAP_INFORMATION, *PDEBUG_HEAP_INFORMATION;
    
    // RtlQueryProcessDebugInformation.DebugInfoClassMask constants
    #define PDI_MODULES                       0×01
    #define PDI_BACKTRACE                     0×02
    #define PDI_HEAPS                         0×04
    #define PDI_HEAP_TAGS                     0×08
    #define PDI_HEAP_BLOCKS                   0×10
    #define PDI_LOCKS                         0×20
    
    extern “C”
    __declspec(dllimport)
    NTSTATUS
    __stdcall
    RtlQueryProcessDebugInformation(
    IN ULONG  ProcessId,
    IN ULONG  DebugInfoClassMask,
    IN OUT PDEBUG_BUFFER  DebugBuffer);
    
    extern “C”
    __declspec(dllimport)
    PDEBUG_BUFFER
    __stdcall
    RtlCreateQueryDebugBuffer(
    IN ULONG  Size,
    IN BOOLEAN  EventPair);
    extern “C”
    __declspec(dllimport)
    NTSTATUS
    __stdcall
    RtlDestroyQueryDebugBuffer(
    IN PDEBUG_BUFFER  DebugBuffer);
    Regards,
    Giuseppe 'Evilcry' Bonfa'
    Categories
    Uncategorized
  5. Anti-Emulation Tricks

    Hi,

    Thanks to Gunther for ARTeam here we have some new Anti-Emulation open source functions, I’ve uploaded these on my OffensiveCOding section:

    here a quick list of the functions:

    Anti-KAV -> Call this one before WSAStartup(),so sockets wont be initialized.
    Anti-NOD32 -> sse1 instruction which nod32 cannot emulate.
    IsEmulator -> Timings Attack to Emulator Environement.
    IsCWSandBox -> Check if CreateProcess is hooked.
    IsAnubis -> Check whether it is running within Anubis.
    IsAnubis2 -> Check whether it is running within Anubis.
    IsNormanSandBox -> NormanSandBox Awareness.
    IsSunbeltSandBox -> Sunbelt Awareness.
    IsVirtualPC -> VirtualPC Awareness.
    IsVMware -> VMware Awareness.
    DetectVM -> Check whether it is running in VMWare, VirtualBox using registry.
    IsRegMonPresent -> Checking for RegMon by checking if the driver is loaded in memory and by searching for the window handle.

    Here the link:

    http://evilcry.netsons.org/OC0/code/EmulationAwareness.c

    See you to the next post..
    Categories
    Uncategorized
  6. Netsons killed my Website

    Hi,
    Netsons without any advice, suspended my account, now I don't have a web-space, if possible I'll try to find some Webspace.

    Regards,
    Giuseppe 'Evilcry' Bonfa'
    Categories
    Uncategorized
  7. Bridge them all

    Today I’m going to tell you something about the last malware I checked (MD5 0C17E03F41289E47EEB5D0F3F1F48C9C).

    The exe file imports few functions only, but the malware calls a lot of APIs. The author uses a special trick to call an API function, he creates a sort of bridge between the first instruction and the rest of the code of the function itself. The first instruction is executed directly from the stack, then a jmp instruction (the bridge) will lead you to the second instruction (and the rest of the code) of the function. I think I’ve already seen the trick somewhere but unfortunately I don’t remember where… maybe a specific packer or just something similar, I don’t know. If you have seen this trick before just drop me a comment, thx!

    The malware is packed, but inside the unpacked file there’s something strange:



    The exe is full of calls to NULL value. I’m pretty sure that it’s not an error occorred during the unpacking process; there’s something at the beginning of the exe able to fix the addresses. I started my analysis from the first lines of the unpacked file.

    The Import Table is really small but spying inside the strings window I found a lot of common API strings. There’s a big list of functions, and they are divided into some groups; one group containing kernel32 functions, another one with user32 and so on. Working a little with some cross references I got the point I was looking for. It’s time to describe how the malware changes all the “call NULL” instructions.

    First of all the malware gains access to kernel32 base address:

    Code:
    4013D5    mov  edi, large fs:30h  ; PEB
    4013DC    mov  edi, [edi+0Ch]     ; PEB+0x00c   Ldr : Ptr32 _PEB_LDR_DATA
    4013DF    mov  edi, [edi+0Ch]     ; +0x00c InLoadOrderModuleList : _LIST_ENTRY
    4013E2    jmp  short loc_401404
    
    4013E4 check_current_module:
    4013E4    mov  eax, edi    ; eax points to current _LDR_MODULE structure
    4013E6    add  eax, 2Ch
    4013E9    push [ebp+arg_0]        ; unicode "kernel32.dll"
    4013EC    push dword ptr [eax+4]  ; current module name inside InLoadOrderModuleList
    4013EF    call Compare_UNICODE_Strings
    4013F4    or   eax, eax
    4013F6    jnz  short strings_are_not_equal
    4013F8    mov  eax, edi           ; LDR_MODULE of the module I was looking for
    4013FA    mov  eax, [eax+18h]     ; He gets the BaseAddress!!!
    4013FD    pop  edi
    4013FE    leave
    4013FF    retn 4
    
    401402 strings_are_not_equal:
    401402    mov  edi, [edi]        ; jump to next module structure
    401404 loc_401404:
    401404    cmp  dword ptr [edi+18h], 0          ; Is BaseAddress 0?
    401408    jnz  short check_current_module
    40140A    xor  eax, eax
    40140C    pop  edi
    40140D    leave
    40140E    retn 4
    Quite common way, but quite uncommon inside a malware… at least from my not so experienced perspective. Anyway, once it has the right BaseAddress tha malware starts bridge-ing all the necessary functions.



    It’s everything inside this call. It takes four parameters, we can ignore the first one pushed into the stack. What about the others?
    - eax represents the BaseAddress of a module, in this case ntdll
    - 404040 points to a sequence of strings, in this case the first one is “RtlZeroMemory”
    - 406000 represents an address inside the malware
    The procedure is called each time the malware needs to bridge a group of functions, all of them belong to a specific module. In this specific case it works with ntdll’s functions. The list of the functions starts from 0×404040 address:



    The routine contains a loop running until all the functions inside the current group are not all bridged. Here is how the first function is bridged (the sub routine starts at 0×401411):
    1. It takes VirtualAlloc starting address via Kernel32’s ExportTable
    2. It gets the number of bytes of the first instruction of VirtualAlloc. On my XP machine VirtualAlloc starts with a two byte length instruction “MOV EDI, EDI”
    3. It subtracts 7 from ESP value. 7 is obtained adding 5 (a fixed value) to the number of bytes of VirtualAlloc first instruction (2+5=7)
    4. It copies the first two bytes of VirtualAlloc’s code inside the word pointed by the new stack pointer value
    5. If the length of the first instruction is one byte only the malware checks for a possible active breakpoint comparing the byte with 0xCC value; quite useless check at this point…
    6. It sets the byte pointed by ESP+2 to 0xE9
    7. It fills the final 4 of 7 bytes obtaining:



    You have the first instruction of VirtualAlloc at 0×12FDF5, then the jump instruction will lead you directly at the second instruction of VirtualAlloc. Now you understand why it decreases ESP value by 7, two bytes for the first instruction and 5 for the jump. Starting from 0×12FDFC you have the old untouched stack.
    8. It gets the length of the first instruction of the function to bridge. In this specific case the name of the function is RtlZeroMemory and the length is 1
    9. It adds 5 to the obtained value
    10. It calls VirtualAlloc passing trought the stack. It calls 0×12FDF5, and it allocs 6 bytes. 6 is the value that comes from point #9 (5+1=6)
    11. It copies the first instruction of RtlZeroMemory inside the allocated memory space
    12. An anti breakpoint check occours this time because the first instruction is one byte only
    13. It sets the second byte inside the allocated memory space to 0xE9 (again, a jmp instruction)
    14. It fills the rest of the bytes:



    Here is the bridge! It’s like what happened to VirtualAlloc, the allocated memory space contains the first instruction of RtlZeroMemory and a jump to the rest of the code
    15. It restores the original stack pointer value simply adding 7 to the current ESP value
    16. It returns the starting address of the allocated memory space (in this case 0×320000)

    To sum up, the routine bridges the function and returns a memory address. The address will be saved starting from 0×406000 which is another parameter passed to the routine. If you don’t remind all the parameters you can take a look some lines above.
    So, starting from 0×406000 you’ll have a series of dwords, each one containing a pointer to a memory allocated space; these are the values used to replace all the NULL calls. Now I finally know why after the unpacking process I still had a series of “call NULL” instructions.

    Is it really necessary to bridge everything?
    Yes if the author wants to fool an automatic analysis. I don’t know if the trick works or not, but it’s the only reasonable thing I can think of.
    On the other hand, he can’t stop a complete human analysis because once you know how it works it’s pretty easy to convert all the “call NULL” instructions into the right ones; a simple idc script will solve the puzzle.

    It’s a nice piece of malware to analyse btw, it has some interesting routines inside!
    Categories
    Uncategorized
  8. Playstation3 / PS3 - Harddisk encryption

    Hey all,

    after I got my first used PS3, i played a bit around with it. The hdd is pretty easy to remove and so i did a full dump of the installed 40 gb hdd. during the dump the hdd contained the data from the former owner.
    next step was to format the disk with the included ps3 format utility. i chose the strong format mode in order to erase the data on the disk. took about 2,5 hours.
    again i made a full dump.
    what i was expecting were two totally different dump. what i found instead was that the first 0x1E bytes were equal.

    you see a small part of the dumps here:

    1.st dump:

    Code:
    00000000 C5 48 55 A0 E6 EE 4F 8F 0A C5 63 AD FA C2 0E 52 .HU...O...c....R
    00000010 30 FA 16 FA C7 F2 FF 55 FE 31 B5 2F 40 40 52 DA 0......U.1./@@R.
    00000020 E2 86 2B 3C 00 D1 2D B1 B8 C4 DE DD E6 EC 12 E3 ..+<..-.........
    00000030 6B 31 C0 0A 9E DE 8A 7C 8C 65 1F 85 B7 22 8E 3A k1.....|.e...".:
    00000040 9D 8D 1E 8A A6 BD 63 96 14 7D 14 BB EF CF B2 F0 ......c..}......
    00000050 E3 E4 10 90 D8 8E 73 94 7A D6 12 CE E8 0C F6 FC ......s.z.......
    00000060 52 C7 55 50 8C 61 F2 DE 5E 00 C3 65 AF 54 13 BC R.UP.a..^..e.T..
    00000070 65 D1 F9 E8 08 C9 64 F6 7D 77 A7 37 D1 94 0B 91 e.....d.}w.7....
    00000080 6E 97 89 3E 17 61 B2 29 BA B7 87 36 C5 51 EC 88 n..>.a.)...6.Q..
    00000090 27 BB D9 6B 0E 1B F8 74 EA B6 15 12 C6 E9 6F 19 '..k...t......o.
    000000A0 10 48 60 AC 0C 0B AF 50 99 0C 6A 11 7A 09 79 AC .H`....P..j.z.y.
    000000B0 97 AD 1F A3 5C B4 15 B4 27 DC DE 6A 2B 16 43 78 ....\...'..j+.Cx
    000000C0 01 28 67 E9 7E B6 22 73 D8 30 03 82 78 1E 6B 05 .(g.~."s.0..x.k.
    000000D0 0B D4 3C 5D 75 0D 95 BB 83 48 DB D6 B2 C7 93 93 ..<]u....H......
    000000E0 37 56 A6 C7 18 0B B4 A4 26 22 C6 7E 6B 02 D9 25 7V......&".~k..%
    000000F0 54 E3 F3 4A 3F 4E CA 21 EB 2F E0 A8 91 4C 2D 4F T..J?N.!./...L-O
    2nd dump:
    Code:
    00000000 C5 48 55 A0 E6 EE 4F 8F 0A C5 63 AD FA C2 0E 52 .HU...O...c....R
    00000010 30 FA 16 FA C7 F2 FF 55 FE 31 B5 2F 40 40 52 DA 0......U.1./@@R.
    00000020 9E F3 C6 89 94 FD C6 2A 62 D9 8F 20 3D 1B 14 9B .......*b.. =...
    00000030 29 A9 04 C2 1D 08 16 3A 09 15 5E DC AF 1C AC AD )......:..^.....
    00000040 F8 70 C4 70 78 48 2F D9 D8 94 90 89 6F D3 DD 42 .p.pxH/.....o..B
    00000050 14 BC 08 05 E7 CF 36 C9 A0 80 DA 58 1F C4 D7 7D ......6....X...}
    00000060 1D AE 34 E6 AF 03 EF 5E E4 B6 B9 F7 E2 5F 9A 9F ..4....^....._..
    00000070 1D B4 D4 81 7D 48 8B C5 D8 FB 82 BE E7 A6 62 FB ....}H........b.
    00000080 0E 4B 8E 21 D6 7B E5 47 03 F9 6D 4B FF 35 05 91 .K.!.{.G..mK.5..
    00000090 41 92 5E 41 C1 24 73 46 E0 27 6A A4 3B AC 14 D0 A.^A.$sF.'j.;...
    000000A0 1D 80 C5 EF DE 19 7A 82 2E A8 7D 95 96 78 76 F6 ......z...}..xv.
    000000B0 1F 9C 01 A0 A6 BF 37 E7 06 C5 11 20 09 3F 33 B6 ......7.... .?3.
    000000C0 76 58 B0 AE 10 3F F4 AA 34 B7 DB 42 3E 31 9F 10 vX...?..4..B>1..
    000000D0 BD BA AD 23 A1 7C B3 3B 41 79 30 7C C4 13 60 EC ...#.|.;Ay0|..`.
    000000E0 48 B0 35 47 C6 B8 7E FF 55 E7 34 97 5C EC F1 FC H.5G..~.U.4.\...
    000000F0 6A F1 34 C0 B6 33 0D 4D 2F F5 C1 B9 BC D7 5F CE j.4..3.M/....._.
    Thats pretty interesting because i thougth that they are using a FULL hardware harddisk encryption. what i found so far is pointing that they also store something encryption/decryption related stuff in these first equal bytes.

    Another interesting fact ist, that both dump can be nearly compressed like text, what is also pretty strange.

    Regards,

    OHPen
    Categories
    PS3 - Homebrew
  9. x64 SEH & Explorer Suite Update

    Yesterday I took a bit of time and updated the Explorer Suite. One important new feauture is the addition of the Exception Directory. I'm no longer working on the old CFF Explorer. However, I thought this feature was too important for people to wait for the new CFF Explorer. Here's a screenshot of the Exception Directory UI:



    If you have no idea how the x64 Structured Exception Handling works, you can briefly read this article on <a href="http://www.osronline.com/article.cfm?id=469">osronline</a> or my article about Vista x64. There's also a pretty in depth quantity of information in a series of posts on <a href="http://www.nynaeve.net/?p=99">Ken Johnson's blog</a>. However, don't hope to find too much information on the web about the real physical layout of the Exception Directory. The MSDN information is incomplete if not wrong and even the SDK doesn't help. This post isn't a complete guide to x64 exceptions, I just want to explain how to analyze them inside the CFF Explorer.

    In the screenshot above you can see two arrays of tables. The first one is an array of RUNTIME_FUNCTION structures. The last column isn't part of this structure though: it shows the five high bits of the first byte of the UNWIND_INFO structure refrenced by the UnwindData member of RUNTIME_FUNCTION. This is the declaration of UNWIND_INFO:

    Code:
    typedef struct _UNWIND_INFO {
        UBYTE Version       : 3;
        UBYTE Flags         : 5;
        UBYTE SizeOfProlog;
        UBYTE CountOfCodes;
        UBYTE FrameRegister : 4;
        UBYTE FrameOffset   : 4;
        UNWIND_CODE UnwindCode[1];
    /*  UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];
    *   union {
    *       OPTIONAL ULONG ExceptionHandler;
    *       OPTIONAL ULONG FunctionEntry;
    *   };
    *   OPTIONAL ULONG ExceptionData[]; */
    } UNWIND_INFO, *PUNWIND_INFO;
    The flags represent the type of handlers. An exception flag represents __try/__except blocks, while the termination flag represents __try/__finally blocks.

    The second is an array of scope records. An UNWIND_INFO can contain more than one scope records. Let's consider this little code sample:

    Code:
    __try
    {
    	__try
    	{
    		// code
    	}
    	__finally
    	{
    		// code
    	}
    	
    	__try
    	{
    		// code
    	}
    	__finally
    	{
    		// code
    	}
    }
    __except (EXCEPTION_EXECUTE_HANDLER)
    {
    	// code
    }
    As you can see from the screenshot, it results in 3 scope records. The HandlerAddress in a scope record structure can be an RVA to a C_exception_handler function. Or it can be a simple value like EXCEPTION_EXECUTE_HANDLER (which is 1). The last scope record represents the __except statement. Don't confuse the exception handler (or filter) with its code.

    The JumpTarget member, if not 0, is an RVA to the exception code. It's possible to see if a particular address has an entry inside the Exception Directory by right clicking on the first table and then clicking 'Is Address Handled' in the pop-up menu. Nevertheless, remember that exception handlers can be added at runtime with APIs like RtlAddFunctionTable and RtlInstallFunctionTableCallback.

    I fixed some minor bugs in the CFF Explorer and one major bug in the Task Explorer. I noticed this bug years ago but never took time to fix it. It showed only when trying to dump the region of an x86 process using the 64 bit version of the Task Explorer. However, x64 is becoming very used and so the bug is now fixed. Also, I thought it a good idea on 64-bit platforms to install a 32-bit version of the Task Explorer and a 64-bit one. Thus, the installer now behaves accordingly.

    Updated January 18th, 2009 at 19:16 by Daniel Pistelli

    Categories
    Uncategorized
  10. Unpinning Importet .dll's

    HI.

    ever wantet to unload a .dll from memory which was importet via the Import Table ? no , well i have , and turns out that windows prevents you from doing this , for security obiviously , as it would be pretty bad to unload a .dll by accident youd later need , but none the less i did some research and found out its more then possible if you preform a little magic , so here are the steps described which are required to do this.

    1) Unpinning dll's

    when windows Loads a .dll into your process space , the .dll is added to the PEB to be more exact in the PEB->LoaderData this Double linked list contains all the Modules Loaded into our image space , lets take a look what it looks like.

    typedef struct _PEB_LDR_DATA
    {
    ULONG Length;
    BOOLEAN Initialized;
    PVOID SsHandle;
    LIST_ENTRY InLoadOrderModuleList;
    LIST_ENTRY InMemoryOrderModuleList;
    LIST_ENTRY InInitializationOrderModuleList;
    }
    PEB_LDR_DATA, *PPEB_LDR_DATA;

    now you see it contains multiple things , for this article the only ones we are interestet in are the 3 LIST_ENTRY's , these 3 are pointers to double linked lists , each entry in the double linked lists contains 1

    typedef struct _LDR_MODULE {
    LIST_ENTRY InLoadOrderModuleList;
    LIST_ENTRY InMemoryOrderModuleList;
    LIST_ENTRY InInitializationOrderModuleList;
    PVOID BaseAddress; PVOID EntryPoint;
    ULONG SizeOfImage;
    UNICODE_STRING FullDllName;
    UNICODE_STRING BaseDllName;
    ULONG Flags;
    SHORT LoadCount; SHORT TlsIndex;
    LIST_ENTRY HashTableEntry;
    ULONG TimeDateStamp;
    } LDR_MODULE, *PLDR_MODULE

    now all this , is various info about our .dll , but lets go back to when Windows Loads a .dll , Everytime you call LoadLibraryA("mydll.dll") windows will add a entry ( if it doesent excist already) and increase the LoadCount by 1 , now what happens when it loads a .dll via our ImportTable ?

    well more or less the same except it sets LoadCount to -1 , which means the .dll is pinned , and if this is the case windows will refuse to unload the .dll from memory.

    So how do we change this ? well take a look at this code:

    bool Mem_Manager::UnPinnAlldlls() {
    OutputDebugStringA("UnPinning All Dll's");
    DWORD PebAddr = 0;
    __asm
    {
    mov eax,DWORD PTR FS:[0x18]
    mov eax,DWORD PTR DS:[eax+0x30]
    mov PebAddr,eax
    }
    PPEB Peb = (PPEB)PebAddr;
    _LDR_MODULE *peb_ldr_module;
    peb_ldr_module = (_LDR_MODULE*)Peb->Ldr->InLoadOrderModuleList.Flink;
    // Go through each modules one by one in their load order. DWORD First = 0; while((DWORD)peb_ldr_module != First)
    {
    if(First == 0)
    {
    First = (DWORD)peb_ldr_module;
    }
    peb_ldr_module->LoadCount = 1;
    peb_ldr_module = (_LDR_MODULE*)peb_ldr_module->InLoadOrderModuleList.Flink;
    }

    return true;
    }

    what happens is:
    1. Gets Addr of PEB via __asm{} block
    2. Access PEB->PEB_LDR_DATA
    3. Get First Loaded Module via : Peb->Ldr->InLoadOrderModuleList.Flink
    4. Log Address of First Entry ( as its a Recursive Double linked list , so we stop once we been all the way round)
    5. Set RefCount of LoadedModule to 1 , so we can unload it with FreeLibrary
    6. Get Next LoadedModule Via: peb_ldr_module->InLoadOrderModuleList.Flink

    so once , these steps have been preformed , you can unload any .dll with a simpel call to FreeLibrary("dllName.dll") and it will be free'd from memory

    hope somebody found this interesting , else oh well
    Categories
    Uncategorized
  11. NtSetDebugFilterState as Anti-Dbg Trick

    The following paper will uncover some intersting Undocumented functions relative to Windows Debugging Support. NT is capable of generating and collecting text Debug Messages with an high grade of customization. User-mode and kernel-mode drivers use different routines to send output to the debugger.

    User Mode: Uses OutputDebugString, that sends a null-terminated string to the debugger of the calling process. In a user-mode driver, OutputDebugString displays the string in the Debugger Command window. If a debugger is not running, this routine has no effect. OutputDebugString does not support the variable arguments of a printf formatted string.

    Kernel Mode: Uses DbgPrint, that displays output in the debugger window. This routine supports the basic printf format parameters. Only kernel-mode drivers can call DbgPrint. There is also DbgPrintEx that is similar to DbgPrint, but it allows you to "tag" your messages. When running the debugger, you can permit only those messages with certain tags to be sent. This allows you to view only those messages that you are interested in.

    This operation is called Filtering Debug Messages, how it works is a little bit undocumented, to understand how to go inside this aspect, let's start from DbgPrint / DbgPrintEx.

    In Windows XP, DbgPrint has been extended by adding _vDbgPrintExWithPrefix, in this way DbgPrint and DbgPrintEx became wrappers of this function.

    Code:
    ULONG
      vDbgPrintExWithPrefix	(
    	IN PCCH	Prefix,
    	IN ULONG    ComponentId,
    	IN ULONG    Level,
    	IN PCCH     Format,
    	IN va_list  arglist
    	);
    vDbgPrintExWithPrefix routine sends a string to the kernel debugger if certain conditions are met. This routine can append a prefix to debugger output to help organize debugging results.

    Let's see what ComponentId means:

    The component that is calling this routine. This parameter must be one of the component name filter IDs that are defined in Dpfilter.h. Each component is referred to in different ways, depending on the context. In the ComponentId parameter of DbgPrintEx, the component name is prefixed with DPFLTR_ and suffixed with _ID. In the registry, the component filter mask has the same name as the component itself. In the debugger, the component filter mask is prefixed with Kd_ and suffixed with _Mask.

    Now let's see Level parameter:

    The severity of the message that is being sent. This parameter can be any 32-bit integer. Values between 0 and 31 (inclusive)) are treated differently than values between 32 and 0xFFFFFFFF.
    Filter masks that are created by the debugger take effect immediately and persist until Windows is restarted.

    The debugger can override a value that is set in the registry, but the component filter mask returns to the value that is specified in the registry if the computer is restarted. There is also a system-wide mask called WIN2000. By default, this mask is equal to 0x1, but you can change it through the registry or the debugger like all other components. When filtering is performed, each component filter mask is first combined with the WIN2000 mask by using a bitwise OR. In particular, this combination means that components whose masks have never been specified default to 0x1.

    By inspecting deeply vDbgPrintExWithPrefix we can see that it represent a wrap around NtQueryDebugFilterState that retrieves the state of the selected Debug Filter Mask. By inspecting xRefs we discover that NtQueryDebugFilterState is also used by DbgQueryDebugFilterState()

    Code:
    NTSTATUS __stdcall DbgQueryDebugFilterState(ULONG ComponentId, ULONG Level)
    0045000C 	ComponentId     = dword ptr  8
    0045000C 	Level           = dword ptr  0Ch
    0045000C
    0045000C     mov     edi, edi
    0045000E     push    ebp
    0045000F     mov     ebp, esp
    00450011     pop     ebp
    00450012     jmp     NtQueryDebugFilterState
    00450012 _DbgQueryDebugFilterState end proc
    As is obvious, DbgQueryDebugFilterState asks for the actual state of Debug Filters. Near the Query function we can see DbgSetFilterState()

    Code:
    NTSTATUS __stdcall DbgSetDebugFilterState(ULONG ComponentId, ULONG Level, BOOLEAN State)
    0045001C     mov     edi, edi
    0045001E     push    ebp
    0045001F     mov     ebp, esp
    00450021     pop     ebp
    00450022     jmp     NtSetDebugFilterState
    00450022     DbgSetDebugFilterState endp
    DbgSetDebugFilterState is a wrapper of a native NtSetDebugFilterState(ULONG ComponentId, ULONG Level, BOOLEAN State)
    As you can understand this is an intersting API cause attempts to modify the Debug Filter Mask:

    Code:
    0056384C NtSetDebugFilterState(ULONG ComponentId, unsigned int Level, char State)
    0056384C	  mov     edi, edi
    0056384E      push    ebp
    0056384F      mov     ebp, esp
    00563851      mov     eax, large fs:124h       ;KTHREAD
    00563857      movsx   eax, byte ptr [eax+140h] ;KTHREAD->PreviousMode
    0056385E      push    eax             
    0056385F      push    ds:_SeDebugPrivilege.HighPart
    00563865      push    ds:_SeDebugPrivilege.LowPart ;PrivilegeValue
    0056386B      call    SeSinglePrivilegeCheck
    00563870      test    al, al
    00563872      jz      short loc_5638BE ;If PrivilegeValue does not match, exit 							and return 0xC00000022 error
    SeSinglePrivilegeCheck checks for the passed privilege value in the context of the current thread, If PreviousMode is KernelMode, the privilege check always succeeds. Otherwise, this routine uses the token of the user-mode thread to determine whether the current (user-mode) thread has been granted the given privilege.
    Here the rest of the function

    Code:
    v3 = &Kd_WIN2000_Mask;
     if ( ComponentId >= KdComponentTableSize )
        {
          if ( ComponentId != 0xFFFFFFFF )
            return 0xC00000EF;
        }
    else
        {
          v3 = (int *)*(&KdComponentTable + ComponentId);
        }
        if ( Level <= 0x1F )
          v4 = 1 << (char)Level;
        else
          v4 = Level;
        v6 = v4;
        if ( !State )
          v6 = 0;
        *v3 = v6 | *v3 & ~v4;
        result = STATUS_SUCCESS;
    Now we can implement a little Anti-Debug trick based on Debug State Awareness, indeed with NtSetDebugFilterState we are able to determine if the process is debugged or not:

    Code:
    #define WIN32_LEAN_AND_MEAN
    #include <Windows.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include "ntDefs.h"
    
    #pragma comment(lib,"ntdll.lib")
    
    int main(void)
    {
    	NTSTATUS ntStatus;
    	
    	ntStatus = NtSetDebugFilterState(0,0,TRUE);
    
    	if (ntStatus != STATUS_SUCCESS)
    		MessageBoxA(NULL,"Not Debugged","Warning",MB_OK);		
    
    	else
    		MessageBoxA(NULL,"Debugged","Warning",MB_OK);
    
    	return (EXIT_SUCCESS);
    -> ntDefs.h

    Code:
    typedef LONG NTSTATUS;
    #define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
    
    extern "C"
    __declspec(dllimport) 
    ULONG __stdcall 
    NtSetDebugFilterState(
    					 ULONG ComponentId,
    					 ULONG Level,
    					 BOOLEAN State					 
    					 );
    Trick is really basilar if the Process is Debugged NtSetDebugFilterState returns STATUS_SUCCESS else returns 0xC00000022 Error Code. May be that this trick is already used, but for sure I haven's seen nothing about NtQueryDebugFilterState/NtSetDebugFilterState =)



    Refs:
    http://msdn.microsoft.com/en-us/library/ms792789.aspx
    http://msdn.microsoft.com/en-us/library/ms804344.aspx


    Thanks to #bug channel especially ratsoul 'n swirl

    Regards,
    Giuseppe 'Evilcry' Bonfa'
  12. Guidelines to MFC reversing

    Tools - References
    Reversing Microsoft Visual C++ Part II: Classes, Methods and RTTI http://www.openrce.org/articles/full_view/23
    IDA http://www.hex-rays.com/idapro
    Crackme http://quequero.org/uicwiki/images/Lezione6.zip

    Prologue: What is MFC?
    The Microsoft Foundation Classes Library (also Microsoft Foundation Classes or MFC) is a library that wraps portions of the Windows API in C++ classes, including functionality that allows to use a default application framework. Classes are defined for many of the handle-managed Windows objects and also for predefined windows and common controls.

    Introduction
    Software developed with MFC may import MFC80U.dll (MFC80U is the name of the last version of the dll, as I'm writing), it depends on the type of compilation: as a static library or as a shared DLL.
    I'll analyze a software which imports the dll and has debug infos, just to make the job easier.
    Once you understand MFC in this way, you can analyze MFC software compiled statically just adding to IDA the signatures of MFC and VisualC.

    Essay
    This is a standard C source code for windows:
    Code:
    LRESULT CALLBACK DialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
            switch(uMsg)
            {
            case WM_COMMAND:
                    switch(LOWORD(wParam))
                    {
    
                    case IDC_ABOUT:
                            DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_DIALOG1), NULL, (DLGPROC)MainDialogProc, 0);
                            break;
                           
                            // ...
                    }
            }
    }
    Instead this is source code that uses MFC:
    Code:
    class CAboutDlg : public CDialog
    {
    public:
            CAboutDlg();
    
    // Dialog Data
            enum { IDD = IDD_ABOUTBOX };
    
    protected:
            virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
    
    // Implementation
    protected:
            DECLARE_MESSAGE_MAP()
    };
    
    CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)  //CAboutDlg::IDD is dialog ID          
    {
    }
    
    void CAboutDlg::DoDataExchange(CDataExchange* pDX)
    {
            CDialog::DoDataExchange(pDX);
    }
    
    BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //Dialog Message Map: is like DialogProc
    END_MESSAGE_MAP()
    
    // App command to run the dialog
    void CProvaRevApp::OnAppAbout()
    {
            CAboutDlg aboutDlg;
            aboutDlg.DoModal();
    }
    How you can imagine the disasm of MFC software is harder to understand.

    MFC Main
    This is the Main disasm of our target:
    Code:
    .text:00401CBB                 public start
    .text:00401CBB                 call    ___security_init_cookie
    .text:00401CC0                 jmp     ___tmainCRTStartup
    
    .text:004019FB ___tmainCRTStartup proc near            ; CODE XREF: start+5�j
    .text:004019FB
    .text:004019FB                 push    5Ch
    .text:004019FD                 push    offset unk_403DD8
    .text:00401A02                 call    __SEH_prolog4
    ;... other initialization code
    .text:00401B3E                 push    ecx             ; nShowCmd
    .text:00401B3F                 push    eax             ; lpCmdLine
    .text:00401B40                 push    ebx             ; hPrevInstance
    .text:00401B41                 push    400000h         ; hInstance
    .text:00401B46                 call    _wWinMain@16    ; wWinMain(x,x,x,x)
    
    ; int __stdcall wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
    _wWinMain@16 proc near
            jmp     ?AfxWinMain@@YGHPAUHINSTANCE__@@0PA_WH@Z ; AfxWinMain(HINSTANCE__ *,HINSTANCE__ *,wchar_t *,int)
    _wWinMain@16 endp
    As you can see WinMain calls AfxWinMain.
    If you have VisualStudio you can see MFC source code, in this article I'll report only the functions we'll need.
    Code:
    int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
            _In_ LPTSTR lpCmdLine, int nCmdShow)
    {
            ASSERT(hPrevInstance == NULL);
    
            int nReturnCode = -1;
            CWinThread* pThread = AfxGetThread();
            CWinApp* pApp = AfxGetApp();
    
            // AFX internal initialization
            if (!AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow))
                    goto InitFailure;
    
            // App global initializations (rare)
            if (pApp != NULL && !pApp->InitApplication())
                    goto InitFailure;
    
            // Perform specific initializations
            if (!pThread->InitInstance())
            {
                    if (pThread->m_pMainWnd != NULL)
                    {
                            TRACE(traceAppMsg, 0, "Warning: Destroying non-NULL m_pMainWnd\n");
                            pThread->m_pMainWnd->DestroyWindow();
                    }
                    nReturnCode = pThread->ExitInstance();
                    goto InitFailure;
            }
            nReturnCode = pThread->Run();
    
    InitFailure:
            AfxWinTerm();
            return nReturnCode;
    }
    This is the disasm of AfxWinMain:
    Code:
    .text:7831D2D2                 public AfxWinMain
    .text:7831D2D2 AfxWinMain      proc near
    .text:7831D2D2                 push    ebx
    .text:7831D2D3                 push    esi
    .text:7831D2D4                 push    edi
    .text:7831D2D5                 or      ebx, 0FFFFFFFFh
    .text:7831D2D8                 call    AfxGetModuleThreadState
    .text:7831D2DD                 mov     esi, [eax+4] ;pThread
    .text:7831D2E0                 call    AfxGetModuleState
    .text:7831D2E5                 push    [esp+0Ch+arg_C]
    .text:7831D2E9                 mov     edi, [eax+4]  ;pApp
    .text:7831D2EC                 push    [esp+10h+arg_8]
    .text:7831D2F0                 push    [esp+14h+arg_4]
    .text:7831D2F4                 push    [esp+18h+arg_0]
    .text:7831D2F8                 call    AfxWinInit
    .text:7831D2FD                 test    eax, eax
    .text:7831D2FF                 jz      short loc_7831D33D
    .text:7831D301                 test    edi, edi    
    .text:7831D303                 jz      short loc_7831D313
    .text:7831D305                 mov     eax, [edi]
    .text:7831D307                 mov     ecx, edi
    .text:7831D309                 call    dword ptr [eax+98h]
    .text:7831D30F                 test    eax, eax
    .text:7831D311                 jz      short loc_7831D33D
    .text:7831D313
    .text:7831D313 loc_7831D313:
    .text:7831D313                 mov     eax, [esi]
    .text:7831D315                 mov     ecx, esi
    .text:7831D317                 call    dword ptr [eax+58h]
    .text:7831D31A                 test    eax, eax
    .text:7831D31C                 jnz     short loc_7831D334
    .text:7831D31E                 cmp     [esi+20h], eax
    .text:7831D321                 jz      short loc_7831D32B
    .text:7831D323                 mov     ecx, [esi+20h]
    .text:7831D326                 mov     eax, [ecx]
    .text:7831D328                 call    dword ptr [eax+68h]
    .text:7831D32B
    .text:7831D32B loc_7831D32B:
    .text:7831D32B                 mov     eax, [esi]
    .text:7831D32D                 mov     ecx, esi
    .text:7831D32F                 call    dword ptr [eax+70h]
    .text:7831D332                 jmp     short loc_7831D33B
    .text:7831D334
    .text:7831D334 loc_7831D334:
    .text:7831D334                 mov     eax, [esi]
    .text:7831D336                 mov     ecx, esi
    .text:7831D338                 call    dword ptr [eax+5Ch]
    .text:7831D33B
    .text:7831D33B loc_7831D33B:  
    .text:7831D33B                 mov     ebx, eax
    .text:7831D33D
    .text:7831D33D loc_7831D33D:
    .text:7831D33D                 call    AfxWinTerm
    .text:7831D342                 pop     edi
    .text:7831D343                 pop     esi
    .text:7831D344                 mov     eax, ebx
    .text:7831D346                 pop     ebx
    .text:7831D347                 retn    10h
    .text:7831D347 AfxWinMain      endp
    In the code there are calls as call [eax+XXh]: actually the call to AfxGetApp (and AfxGetThread) gives back a pointer to a structure that has offsets of all functions used by MFC framework.
    In this case edi (pApp) holds the offset of 405498, which value is 40349C VA, where the virtual functions table of CWinApp is stored:
    Code:
    .rdata:0040349C off_40349C      dd offset ?GetRuntimeClass@CWinApp@@UBEPAUCRuntimeClass@@XZ ;CWinApp::GetRuntimeClass(void)
    .rdata:004034A0                 dd offset sub_401010
    .rdata:004034A4                 dd offset nullsub_1
    .rdata:004034A8                 dd offset nullsub_2
    .rdata:004034AC                 dd offset nullsub_1
    .rdata:004034B0                 dd offset ?OnCmdMsg@CCmdTarget@@UAEHIHPAXPAUAFX_CMDHANDLERINFO@@@Z ; CCmdTarget::OnCmdMsg(uint,int,void *,AFX_CMDHANDLERINFO *)
    .rdata:004034B4                 dd offset ?OnFinalRelease@CCmdTarget@@UAEXXZ ; CCmdTarget::OnFinalRelease(void)
    .rdata:004034B8                 dd offset ?IsInvokeAllowed@CCmdTarget@@UAEHJ@Z ; CCmdTarget::IsInvokeAllowed(long)
    ...
    Categories
    Uncategorized
  13. IOCTL-Proxy

    This is a POC of IOCTL fuzzer. It gave surprisingly good results.

    IOCTL-Proxy works by hooking NtDeviceIoControlFile, manipulating its' parameters and feeding them to the real function.

    Load the driver and simply click around in application you want to test.

    You will get a lot of BSODS, be careful.

    PreviousMode==KernelMode is ignored, since we are only interested in calls from UserMode to KernelMode, not Kernel->Kernel.

    Get it here:
    http://www.orange-bat.com
    Categories
    Uncategorized
  14. Dynamic C++ Proposal

    As anticipated, I just finished my Dynamic C++ proposal. This is not a reversing related article, but a good knowledge of C++ internals and assembly is necessary to read it. I'm glad I'm it's over, frankly. I'd like to thank my friend Quake2 for all his support during the last month.

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

    I wrote this document because I needed to express myself about this subject. Despite the fact that C++ is one of the most used programming language, especially for serious projects, it gets much criticism for being messy, bloated, complicate etc. I believe these critics miss the point. Yes, C++ is a very powerful programming language and that's why it is difficult. And this is also why sometimes C++ source codes are poorly written. I don't believe in improvements of C++ resulting in a new programming language. All attempts in that direction have failed. I think that C++ is here to stay for many reasons. Not only because of the amount of code already available in C++, but also because at the moment there isn't a better programming language for large projects. The only thing I want is for C++ to evolve, but not by losing compatibility with older code or by removing some features. No, I'd like C++ to evolve in a healthy and compatible way. This paper contains the suggestions to achieve this and I will demonstrate technically how it can be implemented at low level.

    Everybody should be warned that the material contained in this paper is purely theoretical. The first idea behind this paper came out while working on a particular project. At the time I discovered myself in need of particular dynamic features. So, for many months I had some ideas in the background of my mind and decided eventually to write them down. So, in this paper I'm going to talk about the current status of dynamism for C++, why dynamism is important and what could be done. At the time of writing (November 2008) the new C++0x (or C++09) standard has not yet been introduced. However, I will talk about it throughout this paper when the related topic is affected by it.

    Updated December 17th, 2008 at 18:01 by Daniel Pistelli

    Categories
    Uncategorized
  15. Command line version of OSR's DeviceTree

    Get it here: http://orange-bat.com/code/device.tree.cmd.rar

    Sample output:

    Code:
    Unloading ObjInfo driver
    Loading driver: D:\tools\devicetree\i386\OBJINFO.SYS
    No service, creating...
    Service not running, starting...
    Service started.
    Driver object: 0x89c98a08
    Service name: nvata
    Device name: \Device\00000138, type: 0x00000007
    Device name: \Device\NvAta2, type: 0x00000001
    Device name: \Device\NvAta1, type: 0x00000001
    Device name: \Device\NvAta0, type: 0x00000001
    
    Driver object: 0x89c8a8d0
    Service name: NDIS
    Device name: \Device\Ndis, type: 0x00000012
    
    Driver object: 0x89cdad28
    Service name: KSecDD
    Device name: \Device\KsecDD, type: 0x00000039
    
    Driver object: 0x8897b218
    Service name: Beep
    Device name: \Device\Beep, type: 0x00000001
    
    Driver object: 0x899e7418
    Service name: Raspti
    Device name: \Device\{AA56C973-4F1C-4D19-8BAC-4FA6F14D80CB}, type: 0x00000017
    
    Driver object: 0x89aab928
    Service name: Mouclass
    Device name: \Device\PointerClass1, type: 0x0000000f
    Device name: \Device\PointerClass0, type: 0x00000000
    .
    .
    .
    It's useful when coding IOCTL fuzzer for example
    Categories
    Uncategorized