All Blog Entries

  1. Education

    If you're someone who already has a reasonable grasp of reverse engineering and malware analysis, I need your help. I need you to help train more people like yourself.

    More likely than not you're "self-taught". Except, when you were teaching yourself you were probably actually relying in large part on the help of others. They freely posted zines, articles, and blog entries. They answered questions in forums, email lists, and in person. Eventually, once you were confident enough to believe you would be right more often than wrong, you might have tried to pay it forward and share your knowledge back to others.

    If so, you're the type of person who is needed. We need people who want to make an impact by more rapidly helping educate those who want to learn. We all know that things like certifications and most college curriculums set a fairly low bar for the expectation of what people should know for security. Certainly in the area of reverse engineering there is almost nothing. Paid training classes can good, but the cost can prevent people from getting all the training they really need.

    I believe what's needed are many more people teaching trainings in person, while encouraging their top students to eventually also become instructors. This brings down costs, provides a well-structured learning environment with instant feedback, and results in the education of many more people. If you're a person who already knows the material, becoming an instructor should be a snap. All you need are class materials, and a venue. Finding venues is up to the instructors, but now there is a place that lesson plans and class materials can be stored:

    This site is meant to act as a repository for class material that have been used in computer security classes at least a day long. The material must be released under an open license to allow the most possible instructors to utilize and adapt the material. It can then be used by new instructors as-is, or piecemeal to enhance or speed the creation of other classes. I didn't want to widely promote the site until we had enough seed content, and now I think we're there.

    But we need more content, and more instructors. If you have classes on any security subject that you currently or have previously taught, and you would like others to use the material, please consider contributing it. And if you're one of the people who already knows a great deal of the material currently posted there, please start thinking about how you could take the material and start teaching others in person, at your job, at conferences, or elsewhere. For more about why you should contribute, and why you should teach, please read this page:


    Xeno Kovah

    Updated December 4th, 2011 at 11:31 by xsk (not sure how a bunch of *s got added into the last edit)

  2. connect two virtual machines on one physical host and use wdeb386 to debug win98 app

    i started reversing and during my first few days i somehow installed softice 4.05 which never worked in windows 2000 then i got to know about ollydbg that was version 1.04 then and it has been my favourite since then

    but ollydbg is a ring 3 debugger and at times when you needed to know what is happening on the other side i felt handicapped

    i didnt want to use softice and windbg needed two machines which was not feasible

    then i used the Poor man's Kernel Debugger livekd from sysinternals

    then i got to know about microsoft virtual pc and i was quiet happy to use it for kernel debugging

    connected to the physical machine using NamedPipe

    if you notice my statements you will find all the software i used were freeware i never had to
    patch or use keygens or scour the net for warej

    but on and off i would be in a situation where my physical host being xp wasnt able to kernel debug some old app in an old os
    like windows 98

    in situations like this it was softice in say 98 vm which i disliked

    so on and off i was trying to connect two virtual machines and use windbg

    but i never succeded in connecting two virtual machine on a single physical host using
    microsoft virtual pc

    vmware was known to me but vmware was either 30 day trial or an endless scouring on bottomless net

    vmware in the meantime released thier player which was freeware but when i looked at it then
    it didnt have the ability to create a vm

    recently i needed to debug some win98 app and i started searching the net for any pointers

    while searching i got to know about vmware player 4.01 which is a freeware and which had the ability to create a vm

    my interest was thus aroused

    and i downloaded the vmware player 4.01 and installed it and started playing with it to create a guest os

    and there by i got to know that vmware has a convertor wherby i can use my old virtual hard disks made by microsoft virtual pc

    so i downloaded the vmware vcenter convertor and installed it

    fed it with a win98.vmc

    and it happily converted the .vmc into a .vmx file and .vhd file into a .vmkd file

    and it loaded perfectly well into vmware (vmware says supported guest os starts from NT )

    after some found newhardware restart routine (omg how many restarts win98 needs )

    i was able to play loderunner on this win98 )

    now moving on to the real purpose

    i fed the convertor another win98se.vmc and got it converted to vmkd and started this too

    i used old ms vpc vhds because i already had lots of craps installed inside them including RTERM98 and WDEB386
    while i fruitlessly tried to use them earlier

    now i had two vms running side by side on a single physical host

    one vm win98 was installed with win98se os and had windows98ddk installed on it

    i had edited the system.ini located in c:\windows

    and added the following in
    [386en] section
    Device= c:\windows\wdeb98.exe
    DebugPort = 1
    DebugBaud = 115200
    DebugSym="full path to sym file" viz "c:\sym\krnl386.sym" "etc etc "
    on the other vm i had a win98se os and in that i had RTERM98 open connected to comport 1

    on both vmware player i added a serial port
    asked vmware to use named pipe \\.\pipe\com_1 on both vms

    assigned one end as server and other end as virtual machine in first vm
    assigned one end as cilent and other end as virtual machine in second vm

    and restarted the first vm which had WDEB98 installed and kept the finger crossed

    but to my surprise rterm98 on the other vm sprang to life and started spouting up

    the time was well spent i can now set a int 3 in some .com file or LE or NE or VXD and stop in kernel debugger

    and all freeware at that

    i post below a few screen shots for clarity and some debug spew from rterm

    i opened up my fav iczelion tut 02 msgbox.exe plopped an int aka 0xcc at 0x401000
    double clciked it and got it trapped in wdeb386 see screen shot
    Attached Thumbnails Attached Images    
  3. ApiMapSet Hooking

    I wrote about new technique of hijacking some APIs on Windows 7 via ApiMapSet.

    small description :
    source code :
  4. ApiMapSet Explained

    I try to explain how all redirection are done in Windows 7 through dlls such as api-ms-win-core-console-l1-1-0.dll and similar
  5. Simple Dll Compiled From Commandline Unlike what google returns vc++ proj

    Sometimes Google in its infinite wisdom will never get you what you remember you saw earlier in the same Google come what may or use whatever search term you may imagine

    so i was searching for this simple dll tutorial which i vividly remember and i couldn't find it

    and hence this blog

    so you want to create a dll and you want to do it in command line
    not using start->program->vs->new->project->name->win32->console->crap>dll>bs->whatever->magic->finish->stdafx.h->pch->build f7->search the whole comp for dll

    ok here is how you do it

    make a new directory somewhere the dir i created is named NOFIXED

    add these files to the directory

    NOFIXED:\>dir /b
    AddNumbers.c is the source code for dll and it contains

    NOFIXED:\>type AddNumbers.c
    #include <windows.h>
    #include "AddNumbers.h"
    BOOL WINAPI DllMain(
        HINSTANCE hinstDLL,
        DWORD fdwReason,
        LPVOID lpReserved ){
                    switch( fdwReason ){
                            case DLL_PROCESS_ATTACH:
                            case DLL_THREAD_ATTACH:
                            case DLL_THREAD_DETACH:
                            case DLL_PROCESS_DETACH:
                    return TRUE;
    _declspec (dllexport) ULONG AddNumbers(ULONG a, ULONG b){
    AddNumbers.h is the Header File You Would Need To Link To The Dll when You Create An EXE and it contains

    NOFIXED:\>type AddNumbers.h
    #include <windows.h>
    BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason,LPVOID lpReserved );
    _declspec (dllexport) ULONG  AddNumbers(ULONG a, ULONG b);
    AddNumbers.def is the module definition File that is required to Build a Dll and it contains

    NOFIXED:\>type AddNumbers.def
    CallAddNum.c is the source code for the exe that links to the AddNumbers.dll that you are going to Build and Call the function in the dll and it contains

    NOFIXED:\> type CallAddNum.c
    #include <stdio.h>
    #include "AddNumbers.h"
    int main (void){
            printf("3 + 5 = %x\n" , AddNumbers(3,5));
            return 0;
    and finally AddNumbers.Bat contains the command line to build the exe and dll

    and it contains the following commands
    cl is the compiler
    /nologo suppresses copyright message
    /c compiles only no linking
    /LD tells the compiler to create a dll and not an exe
    link is the linker
    /dll tells the linker to link the compiled obj code into a dll
    def:"AddNumbers.def" is the module def file which creates AddNumbers.Lib And AddNumbers.Exp which you use when you compile any exe to link to the dll

    NOFIXED:\>type AddNumbers.bat
    cl  /nologo /c /LD AddNumbers.c
    link /NOLOGO /dll /def:"AddNumbers.def" AddNumbers.obj
    cl /nologo CallAddNum.c AddNumbers.lib
    now open vs2008commandprompt

    start -> program -> microsoft visual c++ 2008 Express Edition -> visual studio tools -> visual studio 2008 command prompt

    navigate to the present NOFIXED Directory
    and run the AddNumbers.bat you should get you dll and exe compiled

    NOFIXED:\>dir /b & AddNumbers.bat & dir /b
    NOFIXED:\>cl  /nologo /c /LD AddNumbers.c
    NOFIXED:\>link /NOLOGO /dll /def:"AddNumbers.def" AddNumbers.obj
       Creating library AddNumbers.lib and object AddNumbers.exp
    NOFIXED:\>cl /nologo CallAddNum.c AddNumbers.lib
    run the exe to check if you have succeeded

    3 + 5 = 8
    that is all for now
  6. How To Add TypeInfo So That Dt Commands Work Properly In Windbg

    How To Add TypeInfo So That Dt Commands Work Properly In Windbg


    SomeTimes When You use Certain Dt Commands In windbg You Are Faced With The Type Information Not Available error

    like below

    lkd> !ca 8657c600
    ControlArea  @ 8657c600
      Segment      00000010  Flink      00000010  Blink        85c4e7a0
      Section Ref         0  Pfn Ref           0  Mapped Views c4000001
      User Ref     31447341  WaitForDel 86c7969c  Flush Count       a08
      File Object  865a3818  ModWriteCount  c66c  System Views     8657
      Flags (1) BeingDeleted 
          No name for file
    Segment @ 00000010
    Type nt!_MAPPED_FILE_SEGMENT not found.
    if we google around we can find this above struct is unoffiicially documented in bits and pieces in several sites
    like Moonsols, msdn.mirt , nirsoft etc

    and most of these structures were pieced together from pdbs themselves

    like we can see this struct in ntkrnlmp.pdb

    F:\SYMBOLS\ntkrnlmp.pdb\998A3472EEA6405CB8C089DE868F26222>grep -i MAPPED_FILE_SE
    GMENT  -b1 -U *.*
    Binary file ntkrnlmp.pdb matches
    F:\SYMBOLS\ntkrnlmp.pdb\998A3472EEA6405CB8C089DE868F26222>grep -i MAPPED_FILE_SE
    GMENT  -a1 -U *.*
    ♥ ↔  ♦ OwnerTable ≤≥: ♣☻  ☻↔         _CM_INTENT_LOCK U_CM_INTENT_LOCK@@ ≤≥
    ♫ ♥#   "     R ♣  ☻              _PROC_IDLE_STATE_ACCOUNTING U_PROC_IDLE_ST
    ♥ ↔   State F ♣♠  ☻↔          └☻_PROC_IDLE_ACCOUNTING U_PROC_IDLE_ACCOUNTIN
    even though it is there windbg cant find it because this struct is probably not referanced

    anyway back to topic

    i had posted a while back how to put the typeinfo back into the respective pdb using wdk

    in this post

    that method is for putting the type info back to respective pdb

    but some times you dont have a pdb to put back

    in situations like this you can use the following approach


    you are on winxp and you are debugging via kd a win 7 vm

    you think the code you are looking at is similar to fastfat in winddk srcs

    an you want the type info for


    in that case

    just compile the following code lets say helloworld.c

    #include	<ntddk.h>
    DRIVER_INITIALIZE				DriverEntry;
    DRIVER_UNLOAD					DriverUnload;
    			 PDRIVER_OBJECT DriverObject
    				 DbgPrint("Driver unloading\n");
    			__in PDRIVER_OBJECT DriverObject,
    			__in PUNICODE_STRING RegistryPath
    				DriverObject->DriverUnload = DriverUnload;
    				DbgPrint("Hello World!\n");
    				return STATUS_SUCCESS;
    this is code for a simple driver that you can load with osr loader and operate with either osrloader or net start / stop "servicename"

    the sources file contains

    SOURCES = HelloWorld.c

    the make file conatins

    C:\WinDDK\7600.16385.1\src\HelloWorld>type makefile
    !INCLUDE $(NTMAKEENV)\makefile.def

    build this with win 7 fre build environemt

    C:\WINDOWS\system32\cmd.exe /k C:\WinDDK\7600.16385.1\bin\setenv.bat C:\WinDDK\7600.16385.1\ fre x86 WIN7
    cd %COMPILEDIR% 
    copy the driver to win7 vm use osrloader to register the sevice and start the service

    if you used auto the driver will load during boot stage and you can simply see the dbg print while booting

    if you enable DEBUG PRINT FILTER mask in kd

    like below

    kd> ed nt!Kd_DEFAULT_Mask 0xf

    Hello World!

    now we want to add type info for


    which does not exist in any pdbs

    kd> dt *!*boot*

    change the earlier code to fatexam.c with the following addition

    #include	<ntddk.h>
    #include	"fat.h"   \\<------------ C:\WinDDK\7600.16385.1\src\filesys\fastfat\Win7
    PACKED_BOOT_SECTOR				packboot;  \\ <---------------------- declaration 
    DRIVER_INITIALIZE				DriverEntry;
    DRIVER_UNLOAD					DriverUnload;
    			 PDRIVER_OBJECT DriverObject
    				 DbgPrint("Driver unloading\n");
    			__in PDRIVER_OBJECT DriverObject,
    			__in PUNICODE_STRING RegistryPath
    				DriverObject->DriverUnload = DriverUnload;
    				DbgPrint("Hello World!\n called from fatexam.sys\n "); 
    				DbgPrint("Testing To See If .Kdfiles Work Dynamically!\n");
    				DbgPrint("use dt fatexam!* to look for typeinfo you just added\n");
    				return STATUS_SUCCESS;
    change the sources file to reflect names and build it

    now about how to transfer the newly built sys to vm via debugger

    we can use the debuggers .kdfiles command

    .kdfiles is a command (Driver Replacement Map) which will replace an existing driver in the target computer being debugged with a
    new one from host computer that is running Windbg

    to use .kdfiles

    make a foo.txt file (may be foo.ini or blah.yuk or whatever.crap file) in any directory

    in that file add the following contents
    C:\WinDDK\7600.16385.1\src>type kdfiles.ini

    if it didnt work first time you may have to change \??\ to just c:\Windows\system32 or maybe %systemroot%\system32

    use ctrl+alt+d to view the debug spew to find the error

    go to windbg command window and type

    .kdfiles C:\WinDDK\7600.16385.1\src\kdfiles.ini (use the directory and filename you chose not what i typed here)

    windbg should say
    kd> .kdfiles C:\WinDDK\7600.16385.1\src\kdfiles.ini
    KD file assocations loaded from 'C:\WinDDK\7600.16385.1\src\kdfiles.ini'
    if you run the .kdfiles without any argument you should see something similar to this
    kd> .kdfiles
    KD file assocations loaded from 'C:\WinDDK\7600.16385.1\src\kdfiles.ini'
    \??\C:\Windows\System32\drivers\fatexam.sys -> C:\WinDDK\7600.16385.1\src\HelloWorld\fatexam\objfre_win7_x86\i386\fatexam.sys
    and thats all

    now if you go to vm and use net start service name
    before the driver is accessed it will be replace by the new one and your type info should be available

    like below

     Driver unloading
    KD: Accessing 'C:\WinDDK\7600.16385.1\src\HelloWorld\fatexam\objfre_win7_x86\i386\fatexam.sys' (\??\C:\Windows\System32\drivers\fatexam.sys)
      File size 4KKdPullRemoteFile(83DE4A70): About to overwrite \??\C:\Windows\System32\drivers\fatexam.sys and preallocate to e00
    KdPullRemoteFile(83DE4A70): Return from ZwCreateFile with status 0
    Hello World!
     called from helloworld.sys
     Testing To See If .Kdfiles Work Dynamically!
    use dt fatexam!* to look for typeinfo you just added

    the results of the ealier command now shows added info

    kd> dt *!*boot*
  7. Some notes on how to find out hidden callbacks

    Can I blog an incomplete solution or an incomplete analysis? Why not! Thats the spirit of this blog entry!

    More than one year ago I started a project with Kayaker, we decided to write a tool able to show hidden callbacks. If I remember correctly the idea was born while we were putting our hands on a rootkit. In the same days I bet there were many reversers around thinking the same thing because the same tool was developed by others. As you can imagine our tool never see the light, but not because there are similar tools available online; mostly because we are two old lazy reversers!

    I bet you are thinking: why the hell are you writing this stupid intro? Well, the tools I mentioned before were bugged and some months ago I discovered the same thing, they are still bugged (I dont know if they have solved their problems right now). Strange that no one else noticed it yet.
    Anyway, we wont complete the tool, but with this blog post I would like to tell you some notes about our investigations. At the beginning I wanted to write a detailed and complete article about the subject, but I dont know when Ill be able to end this project so I decided to spread out some of my notes.

    Its a sort of two minds work so credit goes to Kayaker too!

    The idea is to try to retrieve hidden callbacks that has been installed via CmRegisterCallback, PsSetCreateProcessNotifyRoutine, PsSetCreateThreadNotifyRoutine and PsSetLoadImageNotifyRoutine. After that it would be good to deregister one or more of them.

    Where to start?
    First of all you have to understand whats behind functions like CmRegisterCallback, and others. Then, youll have something to work on. Ill start with CmRegisterCallback (from XP SP2), the function is used to register a RegistryCallback routine, and I think the XP version is the most simple one to fully undestand the principles behind the function. There are some differencies between XP and 7 versions, but I think youll be able to fully understand 7 structure too! Here is the disassembled function (without useless parts of course):
    487E6B  push   'bcMC'                          ; Pool Tag: "CMcb" 
    487E70  xor    ebx, ebx 
    487E72  push   38h                             ; NumberOfBytes: 0x38 
    487E74  inc    ebx 
    487E75  push   ebx                             ; PoolType: PAGEDPOOL 
    487E76  call   ExAllocatePoolWithTag           ; ExAllocatePoolWithTag(x,x,x): allocates pool memory 
    487E7B  mov    esi, eax                        ; eax is the pointer to the allocated pool memory, PCM_CALLBACK_CONTEXT_BLOCK 
    487E7D  xor    edi, edi 
    487E7F  cmp    esi, edi                        ; Is PCM_CALLBACK_CONTEXT_BLOCK a NULL pointer? 
    487E81  jz     cmRegisterCallback_fails        ; yes: function fails... 
    487E87  push   esi 
    487E88  push   [ebp+Function]                  ; PEX_CALLBACK_FUNCTION, pointer to callback function 
    487E8B  call   _ExAllocateCallBack             ; allocates and fill EX_CALLBACK_ROUTINE_BLOCK structure (more on this later...) 
    487E90  cmp    eax, edi                        ; ExAllocateCallback success or not? 
    487E92  mov    [ebp+PEX_CALLBACK_ROUTINE_BLOCK], eax ; store the pointer to the allocated pool memory 
    487E95  jnz    short _ExAllocateCallBack_success   
        ...                                         ; fill CM_CALLBACK_CONTEXT_BLOCK fields 
    487EDC  mov    ebx, offset CmpCallBackVector 
    487EE1  mov    [ebp+i], edi                    ; i = 0 
    487EE4 try_next_slot: 
    487EE4  push   edi                             ; OldBlock: NULL 
    487EE5  push   [ebp+PEX_CALLBACK_ROUTINE_BLOCK] ; NewBlock with information to add 
    487EE8  push   ebx                             ; CmpCallbackVector[i] 
    487EE9  call   _ExCompareExchangeCallBack   ; try to *insert* the new callback inside CmpCallBack vector 
    487EEE  test   al, al                       ;check the result... 
    487EF0  jnz    short free_slot_has_been_found    ; jump if the vector has an empty space for the new entry 
    487EF2  add    [ebp+i], 4                      ; i++, increase the counter 
    487EF6  add    ebx, 4                          ; shift to the next item of the vector to check 
    487EF9  cmp    [ebp+i], 190h                   ; is the end of the vector? 
    487F00  jb     short try_next_slot             ; no: try another one. yes: no free slot!    
    487F11 cmRegisterCallback_fails: 
    487F16 end_CmRegisterCallback:    
    487F1A  retn   0Ch    
    487F1D free_slot_has_been_found: 
    487F1D  mov    eax, 1 
    487F22  mov    ecx, offset _CmpCallBackCount   ; CmpCallBackCount: number of not NULL item inside the vector 
    487F27  xadd   [ecx], eax                      ; there's a new callback, it increases the number of item inside the vector 
    487F2A  xor    eax, eax 
    487F2C  jmp    short end_CmRegisterCallback
    As you can see the idea behind the function is really simple!
    Basically, it tries to add a new entry inside a vector named CmpCallBackVector, and when the entry is correctly inserted the registration process will end with a success.
    How do I know is it using a vector? The add instruction at 0x487EF6 represents a clear clue, and the cmp at 0x487EF9 reveals the fixed length of the vector (the vector has 100 items (0190/4)). Now that I have this information Im going to try to explain the entire procedure in detail. The algorithm could be divided into 5 big blocks:

    1: try to allocate 038 bytes for a structure named CM_CALLBACK_CONTEXT_BLOCK
    2: try to allocate 0x0C bytes for a structure named EX_CALLBACK_ROUTINE_BLOCK
    3: fill CM_CALLBACK_CONTEXT_BLOCK fields
    4: look for an empty slot, insert a sort of PEX_CALLBACK_ROUTINE_BLOCK in it and update CmpCallBackCount
    5: notify success or error and exit

    Point #1 is pretty simple to understand, its only a call to ExAllocatePoolWithTag.

    To understand point #2 you have to see whats going on behind ExAllocateCallBack procedure. Lets start taking a look at it:
    52AB35  push   'brbC'                              ; Pool Tag: Cbrb
    52AB3A  push   0Ch                                 ; NumberOfBytes: 0x0C 
    52AB3C  push   1                                   ; PoolType: PAGED_POOL 
    52AB3E  call   ExAllocatePoolWithTag               ; alloc a EX_CALLBACK_ROUTINE_BLOCK structure 
    52AB43  test   eax, eax                            ; ExAllocatePoolWithTag success or not? 
    52AB45  jz     short _ExAllocateCallBack_fails 
    52AB47  mov    ecx, [ebp+_pex_callback_function]   ; pointer to callback function (PEX_CALLBACK_FUNCTION) 
    52AB4A  and    dword ptr [eax], 0                  ; 1 field: 0 
    52AB4D  mov    [eax+4], ecx                        ; 2 field: _pex_callback_function 
    52AB50  mov    ecx, [ebp+_pool_allocated_memory]   ; PCM_CALLBACK_CONTEXT_BLOCK 
    52AB53  mov    [eax+8], ecx                        ; 3 field: _pcm_callback_context_block 
    52AB56 _ExAllocateCallBack_fails:   
    The procedure is used to allocate and fill a special structure:

    typedef struct _EX_CALLBACK_ROUTINE_BLOCK
           EX_RUNDOWN_REF             RundownProtect;
           PEX_CALLBACK_FUNCTION      Function;
    As you can see from the lines above the first field has been setted to 0 while the other fields are filled with two pointers: the function to register and the context containing info about the callback.

    While point #3 is just a series of mov instructions used to fill CM_CALLBACK_ROUTINE_BLOCK structure, point #4 gives some usefull information to us: CmpCallBackVector has 100 elements and this part of code is used to scan the entire vector until an empty element is found. A failure leads us to a non-registration of the callback. What happens when theres a empty slot inside the vector? The new entry will be added inside the vector. Most of the job is done by the function named ExCompareExchangeCallBack, here is the core of the function:

    52AB81  mov    eax, [ebp+CmpCallbackVector]    ; vector at the current position 
    52AB84  mov    ebx, [eax]                      ; ebx is a PEX_CALLBACK_ROUTINE_BLOCK, the item could be NULL or not 
    52AB86  mov    eax, ebx 
    52AB88  xor    eax, [ebp+OldBlock]             ; OldBlock is NULL for a registration process 
    52AB8B  mov    [ebp+current_pex_callback_routine_block], ebx 
    52AB8E  cmp    eax, 7                          ; check used to see if the current item is NULL or not 
    52AB91  ja     short loc_52ABB5                ; jump if not NULL 
    52AB93  test   esi, esi                        ; is NewBlock NULL? 
    52AB95  jz     short loc_52ABA1                ; jump if it's NULL 
    52AB97  mov    eax, esi                        ; esi, NewBlock pointer (changed...) 
    52AB99  or     eax, 7                          ; PAY ATTENTION HERE: or 7 !?! 
    52AB9C  mov    [ebp+NewBlock], eax             ; change NewBlock pointer: NewBlock = NewBlock OR 7 
    52AB9F  jmp    short loc_52ABA5    
    52ABA5  mov    eax, [ebp+var_4]               ; here if CmpCallbackVector's item is null 
    52ABA8  mov    ecx, [ebp+CmpCallbackVector]    ; current empty slot 
    52ABAB  mov    edx, [ebp+NewBlock]             ; new pointer to insert 
    52ABAE  cmpxchg [ecx], edx                     ; insert the new pointer inside the empty slot! 
    52ABB1  cmp    eax, ebx
  8. Reading Virtual Memory

    During a project i did lately i had to deal with the detection of hidden device drivers... while researching i stumbled upon a problem i came across several years but never had the patience to deal with it, yet now i had to. Well what happened ?! See for yourself:

    I used such pseudocode to scan for the DRIVER_OBJECTs:
    unsigned char * pKernel = 0x80000000;
    for (i = 0; i < KernelSpaceSize; i++)
      	if (pKernel[i] == x)
    at one point the machine simply freezed (no bugcheck) and i couldn't make any clue out of it, this effect was a 100% reproducible.

    I tried pretty much everything to get rid of the problem like using seh, probing the page, physically accessing it etc you name it.

    (Try it for yourself, in windbg do a "s 0 L -1 0xff", at some point it will most likely freeze your machine)

    After further research on this i saw that others faced this problem also, like Joanna Rutkowska, which can't solve the problem either.
    Her solution was to reduce the range of memory that she scans for [a] (which is absolutely bullshit if you ask me).

    To shorten the whole story, the problem arised because some memory areas are mapped to physical devices (memory mapped io) like your graphic card once you touch those areas your machine will go into an undefined state.
    The reason for all this is the north bridge of your motherboard which is the router for those requests, it will decide if the request will be forwarded to your mem chips or if it is an attempt to access a device. [b]

    So how does Windows handle it ?! That's pretty much the first question that came to my mind, because seriously i have never ever seen a "bugcheck" freezing while creating a memory dump.

    The answer is again simple if you know how it works, basically the bios is the key to all of it, the devices "register" their areas and the ntldr queries the bios for the accessible memory areas during boot.

    This is all done via INT 15h, the keyword if you are interested in it is "System Address Map" [c], luckily windows needs to keep track of those areas. It does so in a structure called PHYSICAL_MEMORY_RUN, which is nothing else than an array of elements that tell you the areas that can be touched and which you can't.

    And there you go... as long as you are aware of the limits described in the run's it's all good...






    Updated March 30th, 2011 at 06:48 by ^DAEMON^

  9. The dream is 'really higher up'... :P

    by , March 12th, 2011 at 21:40 (BanMe.From.Native_Development)
    OK so this is a 'blog' entry..what defines a blog?..usually its written by 1 person with some lore about something..sometimes it contains insight to the person writing it, and sometimes it's just nothing..well that isn't how I roll..The dark scowl, calculating eyes, and the 'fuck it I'll help' attitude. Sometimes it shortens, but I am not perfect..

    So I don't really like paying for things when I can find them for free just by trying..

    So I went out and got the intel manuals; indy repeats that everyone needs to read them over and over...( I got ear muffs and blinders as well)...Then while reading that, I needed to have fun or I would go crazy..So I wanted to learn more about I really didn't know shellcoding, before coding that beast in it.. I thought it to be a excellent tool to add to my asm knowledge..

    Then I thought how could I share it and not only teach myself interesting concepts but try to do it in a non destructive way..So I looked around and found the shell coders handbook(s)..along with accompanying code.

    Much of that code is non malicious and should provide a good learning base and its compilable..

    My concept of 'shell code' to explain the dream..:
    1. It should be PIC(position independent code) I.E. it should work, no matter where it is 'placed' in memory...
    2. It should demonstrate kernels of knowledge gathered from many different perspectives and 'schools of thought'.

    But how could I also entangle you the reader to contribute code,and what rules could we all follow to guide us in our explorations?

    I answer my own questions 'contributor rules'

    1. code must not be malicious or infectious(though it can have viral tendencies)
    2. code must not have nulls and the fastcall/syscall convention should be espoused..
    3. code may display omnimorphic qualities and must not have a 'data section' if compiled.
    4. code must not use the 'ldr_data portion of the peb' or API.
    5. other then the above you are free to do as you wish..

    to tickle your mind..
    	xor ecx,ecx;	\
    			;1 dword 'stack'
    	mov ecx,ebx;	/
    	db 064h;	\ useless prefix
    	db 08bh		;mov eax,ebx
    	db 0c3h;	/ret
    	db 0e8h;	\
    			;call to ret
    	dd 0fffffffah;	/
    	mov ecx,dword ptr [esp-4h]; get call return address on stack
    	add ecx,-08h ;minus 8 from return address to point to self stack 
    	mov esp,ecx  ;make the stack internal
    	push ecx;	\
    			;push address of mov eax,ebx to stack and return to it.
    	ret		/

    chapter 1 code..

    this looks simple..and remember it is in the trying that we all learn.

    int triangle (int width, int height){
    int array[5] = {0,1,2,3,4};
    int area;
    area = width * height/2;
    return (area);
    So conceptually compiling this to fastcall...(ie I didn't really do this 'yet').. This function would take width in ecx, and height in edx, then multiply them and divide by 2, and then return the result..

    Updated March 13th, 2011 at 12:19 by BanMe

  10. tracer or Writing tracer without using Windows Debug API

    This time I decided to publish source code of an driver which I used for stealth debugging and tracing protections. I've successfully used it with many packers/protectors but most important projects which I made, and which were using this are themida and aspr 2.3 ske unpackers. Now whole code for this small tracing driver is available at :
  11. Using nt!_MiSystemVaType to navigate dynamic kernel address space in Windows7

    32-bit Windows Vista and later use a feature known as Dynamic Kernel Address Space. To quote from a technical article - the Memory Manager dynamically manages the kernel's address space, allocating and deallocating space to various uses to meet the needs of the system. As a result, the amount of virtual memory being used for internal components, device drivers, the file system cache, kernel stacks, system PTE's, per-session code data structures as well as paged and nonpaged pool memory will grow and shrink based on system activity.

    The key to keeping track of all this dynamic memory lies in the unexported pointer nt!_MiSystemVaType, a mapped array of byte values that describes both the type of memory allocation, and by virtue of the indexed position within the array, the location and size of the memory block. Each time there is a new memory allocation, the MiSystemVaType array is updated.

    In this code project I will try to show how to use MiSystemVaType to navigate the dynamic kernel address space to get a complete mapping of the various allocation types. In addition, I'll give an example of how to use it to find and identify loaded drivers, as well as discuss how it might be used to conduct efficient memory pool searches.

    Here are a few background articles on the subject at hand:

    Understanding the kernel address space on 32-bit Windows Vista

    Inside the Windows Vista Kernel: Part 2

    Windows Internals, Fifth Edition
    9.5.7 Dynamic System Virtual Address Space Management


    nt!_MiSystemVaType is a pointer to an array of byte values of enum type MI_SYSTEM_VA_TYPE. Each byte in the array describes a single Large Page and maps, in sequential order, the entire upper 2GB of logical address space from 0x80000000 (MmSystemRangeStart) - 0xFFFFFFFF. The size of the byte array is either 0x400 when PAE is enabled, where the default size of a Large Page is 2MB, or 0x200 in non-PAE mode, which uses a Large Page size of 4MB.

    The enum type values can be listed with WinDbg/LiveKd:

    kd> dt nt!_MI_SYSTEM_VA_TYPE
       MiVaUnused = 0n0
       MiVaSessionSpace = 0n1
       MiVaProcessSpace = 0n2
       MiVaBootLoaded = 0n3
       MiVaPfnDatabase = 0n4
       MiVaNonPagedPool = 0n5
       MiVaPagedPool = 0n6
       MiVaSpecialPoolPaged = 0n7
       MiVaSystemCache = 0n8
       MiVaSystemPtes = 0n9
       MiVaHal = 0n10
       MiVaSessionGlobalSpace = 0n11
       MiVaDriverImages = 0n12
       MiVaSpecialPoolNonPaged = 0n13
       MiVaMaximumType = 0n14

    PAE mode:

    The Physical Address Extension (PAE) processor feature enables use of 64-bit page table entries for physical addresses that are wider than 32 bits. If PAE is enabled, the size of page table entries (PTEs) are increased from 32 to 64 bits (4 to 8 bytes). Consequently, the size of a Large Page is reduced from 4MB to 2MB in PAE mode. One can determine the size of the PTE data structure, nt!_MMPTE, (and hence if PAE is enabled or not) with the command:

    kd> dt -v nt!_MMPTE
    struct _MMPTE, 1 elements, 0x8 bytes
    To determine if PAE is enabled programmatically we can read the ProcessorFeatures field of KUSER_SHARED_DATA, a shared memory structure mapped to all processes and located at 0x7FFE0000 in usermode. This is equivalent to what the IsProcessorFeaturePresent API does.

    KUSER_SHARED_DATA is duplicated at 0xFFDF0000 in kernelmode. Fortunately ntddk.h gives us a handy macro with which to work with it. The snippet below will give us (by inference) the size of nt!_MMPTE, from which we can derive the size of a large page and the size of the MiSystemVaType array.

    PHP Code:
    #define KI_USER_SHARED_DATA         0xffdf0000
    #define SharedUserData  ((KUSER_SHARED_DATA * const)   KI_USER_SHARED_DATA)

    // Determine if PAE is enabled from  KI_USER_SHARED_DATA.ProcessorFeatures

    DbgPrint ("PAE enabled\n");

    sizeof_MMPTE 8;

    } else {

    DbgPrint ("PAE not enabled\n");

    sizeof_MMPTE 4;

    In the registry the PAE status can be read from
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PhysicalAddressExtension

    Here is a summary of the differences between PAE and non-PAE mode which are relevant to our code:

    (PAGE_SIZE = 0x1000)
    PAE enabled:
        nt kernel version:
             ntkrnlpa.exe: 1 CPU, PAE
             ntkpamp.exe:  n CPU, SMP, PAE
        sizeof_MMPTE = 8
        LARGE_PAGE_SIZE = PAGE_SIZE * PAGE_SIZE / sizeof_MMPTE = 0x200000  (2MB)
        sizeof MiSystemVaType array = (0xFFFFFFFF+1 -  (ULONG)MmSystemRangeStart) / LARGE_PAGE_SIZE = 0x400
        0x400 * 0x200000 = 0x80000000 = (0x80000000 / 1024 /1024 /1024) =  2GB
    PAE disabled:
        nt kernel version:
            ntoskrnl.exe: 1 CPU
            ntkrnlmp.exe: n CPU, SMP
        sizeof_MMPTE = 4
        LARGE_PAGE_SIZE = PAGE_SIZE * PAGE_SIZE / sizeof_MMPTE = 0x400000  (4MB)
        sizeof MiSystemVaType array = (0xFFFFFFFF+1 -  (ULONG)MmSystemRangeStart) / LARGE_PAGE_SIZE = 0x200
        0x200 * 0x400000 = 0x80000000 = 2GB
    PAE is enabled by default in Windows 7, if you wish to test the included code in non-PAE mode use BCDEdit as follows:

    If DEP is enabled, PAE cannot be disabled. Use the following BCDEdit /set commands to disable both DEP and PAE:

    bcdedit /set nx AlwaysOff
    bcdedit /set pae ForceDisable

    To restore:

    bcdedit /set nx Optout (or one of [Optin |OptOut | AlwaysOn])
    bcdedit /set pae ForceEnable

    Finding the unexported pointer nt!_MiSystemVaType:

    We need to programmatically find the offset to nt!_MiSystemVaType. Since this is an unexported pointer we'll have to parse a known kernel function which makes use of the variable. Uh Oh. Production code need not apply . Oh well, this is an RCE forum, right? At least that's better than using a hard-coded value, not as good as using symbols.

    Rather than using a classic byte-pattern search that is often used to find unexported variables, I made use of a clever idea Zairon mentioned to me, that of looking for cross references between code and data sections in order to pick up instances of data variable usage. In essence, derive XREFS similar to IDA.

    I really like Zairon's idea of using XREF analysis over a byte-pattern search method because it's simple, highly adaptable, and is less susceptible to changing byte patterns between different OS kernel versions.

    The function I chose to parse for the offset of MiSystemVaType was the exported MmIsNonPagedSystemAddressValid procedure. The simple algorithm logic I used was: "Scan for the first data XREF to the section called '.data''"

    See the source code for the specific algorithm I implemented, plus a few suggestions for creating a more rigorous algorithm if desired, such as using a length disassembly engine (LDE) to avoid the possibility a false XREF could occur across instructions.

    The simple logic above should be valid for all current 32-bit nt* kernel versions in Windows 7 / Vista / Server 2008. Even better, MmIsNonPagedSystemAddressValid has been deemed to be obsolete and is exported to support existing drivers only, so it's more unlikely to change anytime soon.

    _MmIsNonPagedSystemAddressValid@4 proc
    8B FF                             mov     edi, edi
    55                                push    ebp
    8B EC                             mov     ebp, esp
    53                                push    ebx
    56                                push    esi
    8B 35 18 57 97 82                 mov     esi, ds:_MmSystemRangeStart //  xref to ALMOSTRO
    57                                push    edi
    8B 7D 08                          mov     edi, [ebp+VirtualAddress]
    BB F8 3F 00 00                    mov     ebx, 3FF8h
    3B FE                             cmp     edi, esi
    72 25                             jb      short loc_828F17A8
    8B C6                             mov     eax, esi
    C1 E8 12                          shr     eax, 12h
    8B CF                             mov     ecx, edi
    C1 E9 12                          shr     ecx, 12h
    23 C3                             and     eax, ebx
    23 CB                             and     ecx, ebx
    2B C8                             sub     ecx, eax
    C1 F9 03                          sar     ecx, 3
    8A 81 60 51 95 82                 mov     al, _MiSystemVaType[ecx]  // xref to .data

    Making sense of MiSystemVaType:

    Now that we've got the pointer to nt!_MiSystemVaType, what do we do with it? The first obvious thing is just to list everything out.

    Let's take a look at the first 0x10 bytes of the MiSystemVaType array. Each byte maps a logical address block of LARGE_PAGE_SIZE, beginning at ...
    Attached Thumbnails Attached Files
  12. My Search for knowledge and my explorations There and back and most often in a circle

    by , January 27th, 2011 at 21:19 (BanMe.From.Native_Development)
    So I got tired of overloading 1 section. As I didnt feel I helped anything, glad someone said something...I tend to just do things without thinking it all through first,and then I redo it, over and over, slightly modifying or rethinking my steps it to understand it to the best of my ability... I know it sounds like hell..But I love it..So as Long as you are you and I am me, we are all good..glad to hear any responses..or criticisms..and most hopefully corrections..

    So from now on all my writings will be in this blog and separated more neatly into my areas that I seek to research and develop and that defensive coding or offensive coding neither can do what both can combined..

    So if you haven't read my posting on Optimizing a fastcall with POASM/masm which isnt about optimizing at all is about using the minimalistic approach to get the most done with what is already give to you..if you didn't catch that; sorry to have mislead you..

    My other posting was About Tls not using API..I still have more why this works..and more of my own study to determine how it all works..But anyway I thought of another experiment..I leave that for later(tls 'debug awareness' with a dll loaded into olly...)

    This is the continuation to the posting 'experiment with relocs:finding a API with relocations...If any others can site some research other then mine please I beg of you to do so..

    This is a idea I have NOT finished yet, but it sounds logical to do.. I have identifying factor(s) and a brain and some knowledge in coding.So Im gonna try..

    Locating a Api with the reloc section.I've somewhat explained this to a few people out there..

    So what have I learned about the reloc section in general..

    1.It might contain locations to data that is used by code.

    I am in process of making a hello world with touching EAT, but it wont be pretty..and this method might be suitable for EAF(a paper written by skypher reference below) environments..completely unportable and 'target down to module specific' yea ..unusable everywhere.. ;P

    Ok So ive had time to invest in this, so I wanted to have a 'target' for this example. So I chose the simplest thing I could think of MessageBoxA..But then I added some caveats to this, just to make it funner.. I want this to be a dll that ONLY works in a debugger that debugs dlls similar to Olly.I dont want to import any API's and I dont want any 'data' to be defined..within my code..

    So OFF I went...looking at user32 relocation section and MessageBoxA..and then my brain started to confuse itself... luckily I struck gold by picking this api as there is a cmp of actual data just 7 bytes into this function..

    7E45058A >   8BFF                MOV EDI,EDI
    7E45058C  /. 55                  PUSH EBP
    7E45058D  |. 8BEC                MOV EBP,ESP
    7E45058F  |. 833D [here]BC04477E[is data 'attack surface'] 00    CMP DWORD PTR DS:[7E4704BC],0
    so I know I was wrong in the now deleted code...I make mistake(s) so I decided to visualize it.

    First Collect all the variable for HIOR(DWORD)+LOOR(WORD)+variant between 0 and 0fff = Data vector Point ...

    so user32 has a base address of 7e410000(IN MY SYSTEM)(But note this should in theory work across all windows versions,as TLS and relocations haven't changed(Even though I was tricked by olly into seeing a windows 7 ntdll without relocations(didn't really look closely) and subsequently told otherwise upon discussion of it..)..and to get to my address which is ImageBase + 00000400 + the offset of 591..(a few tricks of the mind in there for my readers..)

    So I then verified this..

    7E49ED38  00 00 04 00 64 00 00 00 82 30 9B 30 EA 30 F7 30  ...d...‚0›000
    7E49ED48  0A 31 42 31 9D 31 BC 31 D3 31 D9 31 F7 31 18 32  .1B1111112
    7E49ED58  2C 32 56 32 68 32 75 32 7D 32 8A 32 CB 32 DB 32  ,2V2h2u2}2Š222
    7E49ED68  EA 32 0A 33 17 33 34 33 3E 33 5A 33 6A 33 74 33  2.3343>3Z3j3t3
    7E49ED78  E7 33 FA 33 1C 34 2C 34 80 34 76 35 81 35 91 35  334,4€4v55‘5
    7E49ED88  A4 35 AA 35 B4 35 99 38 CD 38 94 39 85 3B 4A 3D  555™88”9…;J=
    Then I need to Modify my code in order to work under these circumstances. But this is small task seeing that I documented my code ...To be continued..

    If you got the TLS idea..then Tls debug awareness without debug api is achieved by reading a module section you dont load and 'olly' does...
  13. DbgView patch

    Well, there is small bug in DbgView.exe which caused serious problem to me. It happened earlier, but I was blaming my code. Recently same thing happened to me again, so I decided to investigate, and found simple bug in DbgView.exe which causes system "hang", so I made patch to fix this issue. More details can be found in readme.txt which is included with patch.
  14. Reality Cracking CNN's Bias

    Those of you fond of Fravia's Reality Cracking section might find this Essay worth the download. This is version 0.9, I have an appendix that needs to be cleaned up but can't spare the time now.

    Essay: Is CNN biased?

    Skimmed down public version mirrors (these are missing an unfinished appendix):

    ABSTRACT: Knowing the bias of your news group of choice is vital to maintaining an accurate understanding of current events. Because disinformation and national propaganda movements have brazenly come to be the default form of media over the past several decades ~and~ because reason and logic have been so grotesquely under-endorsed, the need for public scrutiny of news sources has never been greater. This paper covers the topic of propaganda and media bias. It explicitly critiques CNNs coverage of WikiLeaks Iraq War Logs disclosure, in the hopes that what the reader learns here can be applied to preserve against future instances of selective reporting and aggressive tabloid panhandling.

    Comments and suggestions are welcome
  15. IDAQ: The result of 7 months at Hex-Rays

    It is not a mistery that Hex-Rays is preparing for the IDA 6.0 beta program. In this post I'll write a bit about my personal, behind the scenes, experience with the project.

    It took me 7 months to port/rewrite the old VCL GUI of IDA Pro. The new GUI, as it had been already anticipated months ago on the official blog, is Qt based.

    The main difficulties I have faced were mostly not of technical nature, although it was a complex task, but psychological ones. It took a lot of patience and it was very difficult every morning to go to work and to have to see an unfinished product with the old GUI reminding myself how much was still to do.

    What follows is a rough roadmap of my work, I'll mention only the milestones and not the hundreds of smaller parts. It has to be noted that at least for what concerns the docking I wrote most of it before joining Hex-Rays to accelerate the development of the actual GUI once in the company. While Qt has a docking system, it is not as advanced as the one used by the VCL GUI, which is a commercial control. So, I wrote a docking system myself in order to offer all the advanced features the old GUI had.

    January: first impact with the code. Took me a week to grasp the initial concepts to start. Basically at the end of the month I could display disassembly and graph mode of a file. Also, hints, graph overview and disassembly arrows were implemented.

    February: implemented chooser and forms (which I actually completely changed internally, that's why I had to improve them again later on to obtain better backwards compatibility).

    March: marathon month. Implemented every day one or more dialogs/views such as: hex view, cpu regs view, enum view, struct view, options, navigation band, colors, etc. etc. More than 30, some very easy, some advanced controls such as the hex view or the cpu regs view.

    April: two weeks to finish the docking and smaller things.

    May: two weeks to implement the desktop part (the ability to save/restore layouts and options) and smaller things.

    June: fixes, help system and improved the forms implementation.

    July: Hundreds of fixes for the beta.

    While there will be still bugs to fix, I consider the project as completed and I wrote this post to close a chapter for myself.
Page 2 of 11 FirstFirst 123456789 ... LastLast