Oбщий вопрос по хукам

Тема в разделе "WASM.BEGINNERS", создана пользователем csrss, 16 апр 2009.

  1. csrss

    csrss New Member

    Публикаций:
    0
    Регистрация:
    16 апр 2009
    Сообщения:
    1
    Здрасте. У меня общий вопрос по хукам. Сразу замечу что темой занялся недавно ну и разумеется полный ламер(и в хуках и в асме к сожалению ), но хочу разобратся. Короче закачал себе мигбота(это собственно пример загрузки драйвера при помощи ZwSetSystemInformation) с руткит.ком, смотрю в сорци и пытаюсь понять чё к чему. Вот например такой фрагмент кода:

    Код (Text):
    1. NTSTATUS CheckFunctionBytesNtDeviceIoControlFile(){// тут всё ясно
    2.     int i=0;
    3.     char *p = (char *)NtDeviceIoControlFile;
    4. //=========================================================
    5.     // windows 2k
    6.     //The beginning of the NtDeviceIoControlFile function
    7.     //should match:
    8.     //55        PUSH EBP
    9.     //8BEC      MOV EBP, ESP
    10.     //6A01      PUSH 01
    11.     //FF752C    PUSH DWORD PTR [EBP + 2C]
    12. //=========================================================
    13.     // win xp sp 3
    14.     // 8bff | mov edi, edi
    15.     // 55   | push ebp
    16.     // 8bec | mov ebp, esp
    17.     // 6a01 | push 1
    18. //  char c[] = { 0x55, 0x8B, 0xEC, 0x6A, 0x01, 0xFF, 0x75, 0x2C }; // win 2k
    19.     char c[] = {0x8b, 0xff, 0x55, 0x8b, 0xec, 0x6a, 0x01};  // win xp sp3
    20.  
    21.     while(i<7){
    22.         DbgPrint("NtDeviceIoControlFile - 0x%02X ", (unsigned char)p[i]);
    23.         if(p[i] != c[i]){
    24.             return STATUS_UNSUCCESSFUL;
    25.         }
    26.         i++;
    27.     }
    28.     return STATUS_SUCCESS;
    29. }
    30.  
    31. __declspec(naked) my_function_detour_ntdeviceiocontrolfile()// тут не ясно
    32. {
    33.     __asm
    34.     {      
    35.         // exec missing instructions
    36. //      push    ebp             // win 2k
    37. //      mov     ebp, esp
    38. //      push    0x01
    39. //      push    dword ptr [ebp+0x2C]
    40.  
    41.       mov edi, edi              // win xp sp3
    42.       push ebp
    43.       mov ebp, esp
    44.       push 1
    45.  
    46.         // jump to re-entry location in hooked function
    47.         // this gets 'stamped' with the correct address
    48.         // at runtime.
    49.         //
    50.         // we need to hard-code a far jmp, but the assembler
    51.         // that comes with the DDK will not poop this out
    52.         // for us, so we code it manually
    53.         // jmp FAR 0x08:0xAAAAAAAA
    54.         _emit 0xEA
    55.         _emit 0xAA
    56.         _emit 0xAA
    57.         _emit 0xAA
    58.         _emit 0xAA
    59.         _emit 0x08
    60.         _emit 0x00
    61.     }
    62. }
    63.  
    64. VOID DetourFunctionNtDeviceIoControlFile()// тут всё ясно
    65. {
    66.     char *actual_function = (char *)NtDeviceIoControlFile;
    67.     char *non_paged_memory;
    68.     unsigned long detour_address;
    69.     unsigned long reentry_address;
    70.     int i = 0;
    71.  
    72.     // assembles to jmp far 0008:11223344 where 11223344 is address of
    73.     // our detour function, plus one NOP to align up the patch
    74. //  char newcode[] = { 0xEA, 0x44, 0x33, 0x22, 0x11, 0x08, 0x00, 0x90 };// win 2k
    75.     char newcode[] = { 0xEA, 0x44, 0x33, 0x22, 0x11, 0x08, 0x00};   // win xp sp3
    76.     // reenter the hooked function at a location past the overwritten opcodes
    77.     // alignment is, of course, very important here
    78. //  reentry_address = ((unsigned long)NtDeviceIoControlFile) + 8;   // win 2k
    79.     reentry_address = ((unsigned long)NtDeviceIoControlFile) + 7;   // win xp sp3
    80.  
    81.     non_paged_memory = ExAllocatePool(NonPagedPool, 256);
    82.    
    83.     // copy contents of our function into non paged memory
    84.     // with a cap at 256 bytes (beware of possible read off end of page FIXME)
    85.     for(i=0;i<256;i++)
    86.     {
    87.         ((unsigned char *)non_paged_memory)[i] = ((unsigned char *)my_function_detour_ntdeviceiocontrolfile)[i];
    88.     }
    89.  
    90.     detour_address = (unsigned long)non_paged_memory;
    91.    
    92.     // stamp in the target address of the far jmp
    93.     *( (unsigned long *)(&newcode[1]) ) = detour_address;
    94.  
    95.     // now, stamp in the return jmp into our detour
    96.     // function
    97.     for(i=0;i<200;i++)
    98.     {
    99.         if( (0xAA == ((unsigned char *)non_paged_memory)[i]) &&
    100.             (0xAA == ((unsigned char *)non_paged_memory)[i+1]) &&
    101.             (0xAA == ((unsigned char *)non_paged_memory)[i+2]) &&
    102.             (0xAA == ((unsigned char *)non_paged_memory)[i+3]))
    103.         {
    104.             // we found the address 0xAAAAAAAA
    105.             // stamp it w/ the correct address
    106.             *( (unsigned long *)(&non_paged_memory[i]) ) = reentry_address;
    107.             break;
    108.         }
    109.     }
    110.  
    111.     //TODO, raise IRQL
    112.  
    113.     //overwrite the bytes in the kernel function
    114.     //to apply the detour jmp
    115. //  for(i=0;i < 8;i++)          // win 2k
    116.     for(i=0;i < 7;i++)          // win xp sp3
    117.     {
    118.         actual_function[i] = newcode[i];
    119.     }
    120.  
    121.     //TODO, drop IRQL
    122. }
    123.  
    124. NTSTATUS DriverEntry( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath ){
    125.  
    126.     if(STATUS_SUCCESS != CheckFunctionBytesNtDeviceIoControlFile()){
    127.         DbgPrint("Match Failure on NtDeviceIoControlFile!");
    128.         return STATUS_UNSUCCESSFUL;
    129.     }
    130. DetourFunctionNtDeviceIoControlFile();
    131. }
    Ну я так понимаю что смысл в том чтоб NtDeviceIoControlFile вывести из paged pool в nonpaged. Ок, идём дальше. В WinDbg перед исполнением вышепредставленного кода NtDeviceIoControlFile выглядет у меня следующим образом:
    Код (Text):
    1. nt!NtDeviceIoControlFile:
    2. 8058efad 8bff            mov     edi,edi
    3. 8058efaf 55              push    ebp
    4. 8058efb0 8bec            mov     ebp,esp
    5. 8058efb2 6a01            push    1
    6. 8058efb4 ff752c          push    dword ptr [ebp+2Ch]
    7. 8058efb7 ff7528          push    dword ptr [ebp+28h]
    8. 8058efba ff7524          push    dword ptr [ebp+24h]
    9. 8058efbd ff7520          push    dword ptr [ebp+20h]
    10. 8058efc0 ff751c          push    dword ptr [ebp+1Ch]
    11. 8058efc3 ff7518          push    dword ptr [ebp+18h]
    12. 8058efc6 ff7514          push    dword ptr [ebp+14h]
    13. 8058efc9 ff7510          push    dword ptr [ebp+10h]
    14. 8058efcc ff750c          push    dword ptr [ebp+0Ch]
    15. 8058efcf ff7508          push    dword ptr [ebp+8]
    16. 8058efd2 e8a8b8feff      call    nt!NtAddAtom+0x19b (8057a87f)
    А после исполнения вот так:
    Код (Text):
    1. nt!NtDeviceIoControlFile:
    2. 8058efad ea3806c4850800  jmp     0008:85C40638
    3. 8058efb4 ff752c          push    dword ptr [ebp+2Ch]
    4. 8058efb7 ff7528          push    dword ptr [ebp+28h]
    5. 8058efba ff7524          push    dword ptr [ebp+24h]
    6. 8058efbd ff7520          push    dword ptr [ebp+20h]
    7. 8058efc0 ff751c          push    dword ptr [ebp+1Ch]
    8. 8058efc3 ff7518          push    dword ptr [ebp+18h]
    9. 8058efc6 ff7514          push    dword ptr [ebp+14h]
    10. 8058efc9 ff7510          push    dword ptr [ebp+10h]
    11. 8058efcc ff750c          push    dword ptr [ebp+0Ch]
    12. 8058efcf ff7508          push    dword ptr [ebp+8]
    13. 8058efd2 e8a8b8feff      call    nt!NtAddAtom+0x19b (8057a87f)
    Так вот, мой первый вопрос, что вобщем творится от
    8058efad ea3806c4850800 jmp 0008:85C40638
    до
    8058efd2 e8a8b8feff call nt!NtAddAtom+0x19b (8057a87f)
    И что делает функция my_function_detour_ntdeviceiocontrol()?

    А второй вопрос следующий. Мигбот был написан под Win 2k , и исходя из общего концепта, стараюсь немного модифицировать код чтоб работал на Хр ну и на Висте потом. С NtDeviceIoControlFile всё вышло ок, но там собственно не сильно трудится нужно было. Следующая функция – SeAccessCheck. WinDbg view (begin):
    Код (Text):
    1. nt!SeAccessCheck:
    2. 80564948 8bff            mov     edi,edi
    3. 8056494a 55              push    ebp
    4. 8056494b 8bec            mov     ebp,esp
    5. 8056494d 53              push    ebx
    6. 8056494e 33db            xor     ebx,ebx
    7. 80564950 385d24          cmp     byte ptr [ebp+24h],bl
    8. 80564953 0f8480300100    je      nt!CcSetLogHandleForFile+0x263 (805779d9)
    9. 80564959 395d08          cmp     dword ptr [ebp+8],ebx
    10. 8056495c 0f84a4cb0900    je      nt!IoCheckFunctionAccess+0x2099f (80601506)
    11. 80564962 56              push    esi
    12. 80564963 8b750c          mov     esi,dword ptr [ebp+0Ch]
    13. 80564966 391e            cmp     dword ptr [esi],ebx
    14. 80564968 0f85b72d0100    jne     nt!RtlDeleteAtomFromAtomTable+0x3fc (80577725)
    15. 8056496e 57              push    edi
    16. ........
    И модифицированный мною код:
    Код (Text):
    1. NTSTATUS CheckFunctionBytesSeAccessCheck(){
    2.     int i=0;
    3.     char *p = (char *)SeAccessCheck;
    4. //=====================================================
    5.     // win 2k
    6.     //The beginning of the SeAccessCheck function
    7.     //should match:
    8.     //55        PUSH EBP
    9.     //8BEC      MOV EBP, ESP
    10.     //53        PUSH EBX
    11.     //33DB      XOR EBX, EBX
    12.     //385D24    CMP [EBP+24], BL
    13. //====================================================
    14.     // win xp sp 3
    15.     // 8bff   | mov edi, edi
    16.     // 55     | push ebp
    17.     // 8bec   | mov ebp, esp
    18.     // 53     | push ebx
    19.     // 33db   | xor ebx, ebx
    20.     // 385d24 | cmp byte ptr [ebp+24h], bl
    21. //  char c[] = { 0x55, 0x8B, 0xEC, 0x53, 0x33, 0xDB, 0x38, 0x5D, 0x24 };    // win 2k
    22.     char c[] = {0x8b, 0xff, 0x55, 0x8b, 0xec, 0x53, 0x33, 0xdb, 0x38, 0x5d, 0x24};  // win xp sp 3
    23.  
    24. //  while(i<9)
    25.     while (i<11)
    26.     {
    27.         DbgPrint("SeAccessCheck - 0x%02X ", (unsigned char)p[i]);
    28.         if(p[i] != c[i])
    29.         {
    30.             return STATUS_UNSUCCESSFUL;
    31.         }
    32.         i++;
    33.     }
    34.     return STATUS_SUCCESS;
    35. }
    36.  
    37. __declspec(naked) my_function_detour_seaccesscheck()
    38. {
    39.     __asm
    40.     {      
    41.         // exec missing instructions
    42. //      push    ebp         // win 2k
    43. //      mov     ebp, esp
    44. //      push    ebx
    45. //      xor     ebx, ebx
    46. //      cmp     [ebp+24], bl
    47.  
    48.       mov edi, edi      // win xp sp3
    49.       push ebp
    50.       mov ebp, esp
    51.       push ebx
    52.       xor ebx, ebx
    53.       cmp byte ptr [ebp+24h], bl
    54.         _emit 0xEA
    55.         _emit 0xAA
    56.         _emit 0xAA
    57.         _emit 0xAA
    58.         _emit 0xAA
    59.         _emit 0x08
    60.         _emit 0x00
    61.     }
    62. }
    63.  
    64. VOID DetourFunctionSeAccessCheck()
    65. {
    66.     char *actual_function = (char *)SeAccessCheck;
    67.     char *non_paged_memory;
    68.     unsigned long detour_address;
    69.     unsigned long reentry_address;
    70.     int i = 0;
    71.  
    72. //  char newcode[] = { 0xEA, 0x44, 0x33, 0x22, 0x11, 0x08, 0x00, 0x90, 0x90 };// win 2k
    73.     char newcode[] = { 0xEA, 0x44, 0x33, 0x22, 0x11, 0x08, 0x00 };  // win xp sp3
    74. //  reentry_address = ((unsigned long)SeAccessCheck) + 9;   // win 2k
    75.     reentry_address = ((unsigned long)SeAccessCheck) + 11;  // win xp sp3
    76.  
    77.     non_paged_memory = ExAllocatePool(NonPagedPool, 256);
    78.     for(i=0;i<256;i++)
    79.     {
    80.         ((unsigned char *)non_paged_memory)[i] = ((unsigned char *)my_function_detour_seaccesscheck)[i];
    81.     }
    82.  
    83.     detour_address = (unsigned long)non_paged_memory;
    84.    
    85.     *( (unsigned long *)(&newcode[1]) ) = detour_address;
    86.  
    87.     for(i=0;i<200;i++)
    88.     {
    89.         if( (0xAA == ((unsigned char *)non_paged_memory)[i]) &&
    90.             (0xAA == ((unsigned char *)non_paged_memory)[i+1]) &&
    91.             (0xAA == ((unsigned char *)non_paged_memory)[i+2]) &&
    92.             (0xAA == ((unsigned char *)non_paged_memory)[i+3]))
    93.         {
    94.             *( (unsigned long *)(&non_paged_memory[i]) ) = reentry_address;
    95.             break;
    96.         }
    97.     }
    98.  
    99.     for(i=0;i < 11;i++)     // win xp sp3
    100.     {
    101.         actual_function[i] = newcode[i];
    102.     }
    103. }
    Вродебы всё как в оригинале но к сожалению не пашет. После исполнения кода, SeAccessCheck в ВинДбг выглядит так:
    Код (Text):
    1. nt!SeAccessCheck:
    2. 80564948 ea3814e1850800  jmp     0008:85E11438
    3. 8056494f 8b9851730f84    mov     ebx,dword ptr [eax-7BF08CAFh]
    4. 80564955 803001          xor     byte ptr [eax],1
    5. 80564958 0039            add     byte ptr [ecx],bh
    6. 8056495a 5d              pop     ebp
    7. 8056495b 080f            or      byte ptr [edi],cl
    8. 8056495d 84a4cb0900568b  test    byte ptr [ebx+ecx*8-74A9FFF7h],ah
    9. 80564964 750c            jne     nt!SeAccessCheck+0x2a (80564972)
    10. ...
    А в детекторе руткитов картина следующая:

    // Для NtDeviceIoControlFile
    hooked address: 0x8058efad
    relative to export: NtDeviceIoControlFile
    redirect to: -
    in exection path: NtDeviceIoControlFile

    // для SeAccessCheck
    hooked address: 0x80554948
    relative to export: SeAccessCheck
    redirect to: -
    in exection path: NtAssignProcessToJobObject

    А сам вызов функции – сразу BSOD.
    т.е что-то я напартачил сильно и сам не знаю что. И вот хочу спросить что делаю не то и вообще правильным ли путём иду?
     
  2. Clerk

    Clerk Забанен

    Публикаций:
    0
    Регистрация:
    4 янв 2008
    Сообщения:
    6.689
    Адрес:
    РБ, Могилёв
    В глазах рябит от типов..
    Для начала нужно знать причину падения. Крэшдамп в студию.