Translation of hxxp://wasm.ru/article.php?article=hiddndt I was unable to find any policy about article translations on wasm.ru. If admins of wasm.ru or author feels that some rights were violated, please let me or board admins know and this translation will be removed promptly.
My apologies for rather crude English language, both English and Russian are not my native languages. If anyone wishes to correct some grammatical or factual mistakes, he is welcome to do so.
Source codes will not be translated. They are available at the original site.
Many users have got used that Windows NT Task Manager shows all processes, and many consider that it is impossible to hide a process from Task Manager. Actually, process hiding is incredibly simple. There are lots of methods available for such a purpose and there are source codes available. It still amazes me that there are only a few trojans using these methods. Literally only 1 trojan from a 1000 is hidden. I think that trojan authors are lazy, since it requires extra work to hide the process and it is always easier to use ready-made sources and copy-paste them. Therefore we should expect hidden trojan processes in a near future.
Naturally, it is necessary to have protection against hidden processes. Manufacturers of antiviruses and firewals lagging behind as their products are not able to find hidden processes. For this purpose there are only a few utilities from which free-of-charge is only Klister (works only on Windows 2000). All other companies demand considerable money (kao - not true. BlackLight Beta from FSecure is free.). Furthermore, all these utilities can be easily avoided.
All programs available now, use one method for hidden process detection, therefore we have 2 choices:
* think up a method of concealment from a certain principle of detection,
* think up a method of concealment from a certain program, which is much easier.
The user who bought the commercial program cannot change it, and therefore the binding to the concrete program works reliably enough. Therefore the latter method is used in commercial rootkits (for example hxdef Golden edition). The only solution is creation free-of-charge Opensource program for detection of hidden processes. Such program shall employ several detection methods, and therefore would defeat programs concealed from one certain method. Each user can protect against binding to a certain program, it is necessary to take source codes of the program and to alter them to his own liking.
In this article I will discuss the basic methods of detection of hidden processes, show examples of a code using these methods, and to create working program for detection of hidden processes which would meet all above-stated requirements.
Detection in User Mode (ring3)
For the beginning we shall consider simple methods of detection which can be applied in 3 ring, without use of drivers. They are based on fact, that each process generates certain traces of the activity. Based on these traces we can detect hidden process. Such traces include handles opened by process, windows and created system objects. It is simple to avoid from such detection techniques, but for this purpose it is necessary to consider ALL traces left by process. Such stealth mode is not realized in any of public rootkits (unfortunately private versions are not available to me). Usermode methods are simple in implementation, safe to use, and can give a positive effect, therefore their usage should not be neglected.
For the beginning we shall be define data returned by search function, let it be linked lists:
Code:
type
PProcList = ^TProcList;
TProcList = packed record
NextItem: pointer;
ProcName: array [0..MAX_PATH] of Char;
ProcId: dword;
ParrentId: dword;
end;
Acquiring the list of processes by using ToolHelp API
We shall define reference function receiving the list of processes, we shall compare these results to results obtained by all other means:
Code:
{
Acquiring list of processes by using ToolHelp API.
}
procedure GetToolHelpProcessList(var List: PListStruct);
var
Snap: dword;
Process: TPROCESSENTRY32;
NewItem: PProcessRecord;
begin
Snap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if Snap <> INVALID_HANDLE_VALUE then
begin
Process.dwSize := SizeOf(TPROCESSENTRY32);
if Process32First(Snap, Process) then
repeat
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
NewItem^.ProcessId := Process.th32ProcessID;
NewItem^.ParrentPID := Process.th32ParentProcessID;
lstrcpy(@NewItem^.ProcessName, Process.szExeFile);
AddItem(List, NewItem);
until not Process32Next(Snap, Process);
CloseHandle(Snap);
end;
end;
It is obvious that any hidden process will not be found, therefore this function will be used as a reference for hidden process detection.
Acquiring the list of processes by using Native API
The next scanning level will be acquisition a list of processes through ZwQuerySystemInformation (Native API). It is improbable that something will be found out at this level but we should check it anyway.
Code:
{
Acquiring list of processes by using ZwQuerySystemInformation.
}
procedure GetNativeProcessList(var List: PListStruct);
var
Info: PSYSTEM_PROCESSES;
NewItem: PProcessRecord;
Mem: pointer;
begin
Info := GetInfoTable(SystemProcessesAndThreadsInformation);
Mem := Info;
if Info = nil then Exit;
repeat
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
lstrcpy(@NewItem^.ProcessName,
PChar(WideCharToString(Info^.ProcessName.Buffer)));
NewItem^.ProcessId := Info^.ProcessId;
NewItem^.ParrentPID := Info^.InheritedFromProcessId;
AddItem(List, NewItem);
Info := pointer(dword(info) + info^.NextEntryDelta);
until Info^.NextEntryDelta = 0;
VirtualFree(Mem, 0, MEM_RELEASE);
end;
Acquiring the list of processes by using list of opened handles.
Many hidden processes do not hide handles opened by them, hence we can construct the list of processes by enumerating opened handles using ZwQuerySystemInformation.
Code:
{
Acquiring the list of processes by using list of opened handles.
Returns only ProcessId.
}
procedure GetHandlesProcessList(var List: PListStruct);
var
Info: PSYSTEM_HANDLE_INFORMATION_EX;
NewItem: PProcessRecord;
r: dword;
OldPid: dword;
begin
OldPid := 0;
Info := GetInfoTable(SystemHandleInformation);
if Info = nil then Exit;
for r := 0 to Info^.NumberOfHandles do
if Info^.Information[r].ProcessId <> OldPid then
begin
OldPid := Info^.Information[r].ProcessId;
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
NewItem^.ProcessId := OldPid;
AddItem(List, NewItem);
end;
VirtualFree(Info, 0, MEM_RELEASE);
end;
At this stage it is already possible to find out something. But we should not rely on result of such check as hiding handles is as easy as hiding processes, although some persons forget to do it.
Acquiring the list of processes by using list of the windows created by them.
It is possible to construct the list of processes having windows by building a list of all windows registered in the system and calling GetWindowThreadProcessId for each of them.
Code:
{
Acquiring the list of processes by using list of windows.
Returns only ProcessId.
}
procedure GetWindowsProcessList(var List: PListStruct);
function EnumWindowsProc(hwnd: dword; PList: PPListStruct): bool; stdcall;
var
ProcId: dword;
NewItem: PProcessRecord;
begin
GetWindowThreadProcessId(hwnd, ProcId);
if not IsPidAdded(PList^, ProcId) then
begin
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
NewItem^.ProcessId := ProcId;
AddItem(PList^, NewItem);
end;
Result := true;
end;
begin
EnumWindows(@EnumWindowsProc, dword(@List));
end;
Almost no one is hiding windows, therefore this check also allows to detect some processes, but we should not rely on this check very much.
Acquiring the list of processes by use of a direct system call.
To hide a process in user mode, one usually uses code-injection techniques and intercepts ZwQuerySystemInformation from ntdll.dll in all processes.
Functions in ntdll actually are thunks to corresponding functions in a system kernel, and contain system calls (Int 2Eh in Windows 2000 or sysenter in XP), therefore the most simple and effective way to detect processes hidden from Usermode API, will be the direct use of system calls and not using API.
Function replacing ZwQuerySystemInformation for Windows XP looks like this:
Code:
{
ZwQuerySystemInformation for Windows XP.
}
Function XpZwQuerySystemInfoCall(ASystemInformationClass: dword;
ASystemInformation: Pointer;
ASystemInformationLength: dword;
AReturnLength: pdword): dword; stdcall;
asm
pop ebp
mov eax, $AD
call @SystemCall
ret $10
@SystemCall:
mov edx, esp
sysenter
end;
Due to different system call mechanism, for Windows 2000 this code will look differently.
Code:
{
Системный вызов ZwQuerySystemInformation для Windows 2000.
}
Function Win2kZwQuerySystemInfoCall(ASystemInformationClass: dword;
ASystemInformation: Pointer;
ASystemInformationLength: dword;
AReturnLength: pdword): dword; stdcall;
asm
pop ebp
mov eax, $97
lea edx, [esp + $04]
int $2E
ret $10
end;
Now it is necessary to enumerate processes using above mentioned functions, not ntdll. Here is a code that does it:
Code:
{
Acquiring the list of processes by use of a direct system call
ZwQuerySystemInformation.
}
procedure GetSyscallProcessList(var List: PListStruct);
var
Info: PSYSTEM_PROCESSES;
NewItem: PProcessRecord;
mPtr: pointer;
mSize: dword;
St: NTStatus;
begin
mSize := $4000;
repeat
GetMem(mPtr, mSize);
St := ZwQuerySystemInfoCall(SystemProcessesAndThreadsInformation,
mPtr, mSize, nil);
if St = STATUS_INFO_LENGTH_MISMATCH then
begin
FreeMem(mPtr);
mSize := mSize * 2;
end;
until St <> STATUS_INFO_LENGTH_MISMATCH;
if St = STATUS_SUCCESS then
begin
Info := mPtr;
repeat
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
lstrcpy(@NewItem^.ProcessName,
PChar(WideCharToString(Info^.ProcessName.Buffer)));
NewItem^.ProcessId := Info^.ProcessId;
NewItem^.ParrentPID := Info^.InheritedFromProcessId;
Info := pointer(dword(info) + info^.NextEntryDelta);
AddItem(List, NewItem);
until Info^.NextEntryDelta = 0;
end;
FreeMem(mPtr);
end;
This method detects almost 100% of user mode rootkits, for example all versions of hxdef (including Golden).
Acquiring the list of processes by analyzing handles related to them.
There is another method based on handle enumeration. The essence of method consists not in finding handles opened by process in question but in finding handles in other processes related to this process. It might be handle of the process or handle of the thread. When handle of process is found, we can find process PID using ZwQueryInformationProcess. For a thread it is possible to use ZwQueryInformationThread and obtain Id of process. All processes existing in system have been started by someone, hence parent processes will have handles of them (unless they have closed these handles), also handles of all existing processes are available to a server of Win32 subsystem (csrss.exe). Additionally, Windows NT is using Job objects actively, which allows to unite processes (for example all processes by certain user, or certain services), hence when finding handle of Job object, we should use opportunity to obtain IDs of all processes incorporated in it. It can be done by using function QueryInformationJobObject with a class of the information - JobObjectBasicProcessIdList. The code acquiring the list of processes by analyzing handles related to them looks like this:
Code:
{
Acquiring the list of processes by analyzing handles in other processes.
}
procedure GetProcessesFromHandles(var List: PListStruct; Processes, Jobs, Threads: boolean);
var
HandlesInfo: PSYSTEM_HANDLE_INFORMATION_EX;
ProcessInfo: PROCESS_BASIC_INFORMATION;
hProcess : dword;
tHandle: dword;
r, l : integer;
NewItem: PProcessRecord;
Info: PJOBOBJECT_BASIC_PROCESS_ID_LIST;
Size: dword;
THRInfo: THREAD_BASIC_INFORMATION;
begin
HandlesInfo := GetInfoTable(SystemHandleInformation);
if HandlesInfo <> nil then
for r := 0 to HandlesInfo^.NumberOfHandles do
if HandlesInfo^.Information[r].ObjectTypeNumber in [OB_TYPE_PROCESS, OB_TYPE_JOB, OB_TYPE_THREAD] then
begin
hProcess := OpenProcess(PROCESS_DUP_HANDLE, false,
HandlesInfo^.Information[r].ProcessId);
if DuplicateHandle(hProcess, HandlesInfo^.Information[r].Handle,
INVALID_HANDLE_VALUE, @tHandle, 0, false,
DUPLICATE_SAME_ACCESS) then
begin
case HandlesInfo^.Information[r].ObjectTypeNumber of
OB_TYPE_PROCESS : begin
if Processes and (HandlesInfo^.Information[r].ProcessId = CsrPid) then
if ZwQueryInformationProcess(tHandle, ProcessBasicInformation,
@ProcessInfo,
SizeOf(PROCESS_BASIC_INFORMATION),
nil) = STATUS_SUCCESS then
if not IsPidAdded(List, ProcessInfo.UniqueProcessId) then
begin
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
NewItem^.ProcessId := ProcessInfo.UniqueProcessId;
NewItem^.ParrentPID := ProcessInfo.InheritedFromUniqueProcessId;
AddItem(List, NewItem);
end;
end;
OB_TYPE_JOB : begin
if Jobs then
begin
Size := SizeOf(JOBOBJECT_BASIC_PROCESS_ID_LIST) + 4 * 1000;
GetMem(Info, Size);
Info^.NumberOfAssignedProcesses := 1000;
if QueryInformationJobObject(tHandle, JobObjectBasicProcessIdList,
Info, Size, nil) then
for l := 0 to Info^.NumberOfProcessIdsInList - 1 do
if not IsPidAdded(List, Info^.ProcessIdList[l]) then
begin
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
NewItem^.ProcessId := Info^.ProcessIdList[l];
AddItem(List, NewItem);
end;
FreeMem(Info);
end;
end;
OB_TYPE_THREAD : begin
if Threads then
if ZwQueryInformationThread(tHandle, THREAD_BASIC_INFO,
@THRInfo,
SizeOf(THREAD_BASIC_INFORMATION),
nil) = STATUS_SUCCESS then
if not IsPidAdded(List, THRInfo.ClientId.UniqueProcess) then
begin
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
NewItem^.ProcessId := THRInfo.ClientId.UniqueProcess;
AddItem(List, NewItem);
end;
end;
Unfortunately, some of the above-stated methods allow to acquire only ProcessId, but not a name of process. Hence, we need to be able to get a name of process for PID. Of course, we should not use ToolHelp API for this purpose as this process might be hidden. Therefore we shall open process memory for reading and get a name from its PEB. PEB address can be acquired by using ZwQueryInformationProcess function. Here is a code that does all this:
Code:
function GetNameByPid(Pid: dword): string;
var
hProcess, Bytes: dword;
Info: PROCESS_BASIC_INFORMATION;
ProcessParametres: pointer;
ImagePath: TUnicodeString;
ImgPath: array[0..MAX_PATH] of WideChar;
begin
Result := '';
ZeroMemory(@ImgPath, MAX_PATH * SizeOf(WideChar));
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, Pid);
if ZwQueryInformationProcess(hProcess, ProcessBasicInformation, @Info,
SizeOf(PROCESS_BASIC_INFORMATION), nil) = STATUS_SUCCESS then
begin
if ReadProcessMemory(hProcess, pointer(dword(Info.PebBaseAddress) + $10),
@ProcessParametres, SizeOf(pointer), Bytes) and
ReadProcessMemory(hProcess, pointer(dword(ProcessParametres) + $38),
@ImagePath, SizeOf(TUnicodeString), Bytes) and
ReadProcessMemory(hProcess, ImagePath.Buffer, @ImgPath,
ImagePath.Length, Bytes) then
begin
Result := ExtractFileName(WideCharToString(ImgPath));
end;
end;
CloseHandle(hProcess);
end;
Naturally, usermode detection methods do not end here. It is possible to think up some new methods with a little effort (for example, loading of the Dll in accessible processes by use of SetWindowsHookEx with the subsequent analysis of the list of processes where our Dll has been loaded) but for now we will settle with above mentioned methods. Advantages of these methods are that they are simple in programming, and they allow to detect processes hidden in User Mode, or poorly hidden Kernel Mode processes.. For really reliable detection of hidden processes we should write a driver and work with Windows kernel internal structures.
Kernel Mode detection
Congratulation, we made til kernel-mode hidden process detection. Smile The main difference between these methods and usermode methods is that all lists of processes are created bypassing API calls and directly using scheduler (?) structures. It is much harder to hide from these detection methods,because these methods are based on same principles as Windows kernel and removing process from all scheduler structures will effectively disable this process altogether.
What is the process inside the kernel? Each process has the address space, descriptors, threads, etc. There are structures in the kernel related to these things. Each process is described by EPROCESS structure, structures of all processes are connected in the circular doubly-linked list. One of methods of process hiding consists in changing of pointers so that enumeration skips hidden process. Not being enumerated does not influence process' ability to function. However, EPROCESS structure always should exist, it is required for a process to function. The majority of methods of detection of hidden processes in Kernel Mode are somehow connected with detection of this structure.
Again we shall define format how received process information will be stored. This format should be convenient for data transfer from the driver (in the appendix). Let it will the following structure:
Let this function be our reference function as any Kernel Mode hidden processes will not be detected. But all user mode root-kits like hxdef will be detected.
In this code we use function GetInfoTable to obtain information easily. To avoid questions about what is that, here is complete code of function:
Code:
/*
Receiving buffer with results from ZwQuerySystemInformation.
*/
PVOID GetInfoTable(ULONG ATableType)
{
ULONG mSize = 0x4000;
PVOID mPtr = NULL;
NTSTATUS St;
do
{
mPtr = ExAllocatePool(PagedPool, mSize);
memset(mPtr, 0, mSize);
if (mPtr)
{
St = ZwQuerySystemInformation(ATableType, mPtr, mSize, NULL);
} else return NULL;
if (St == STATUS_INFO_LENGTH_MISMATCH)
{
ExFreePool(mPtr);
mSize = mSize * 2;
}
} while (St == STATUS_INFO_LENGTH_MISMATCH);
if (St == STATUS_SUCCESS) return mPtr;
ExFreePool(mPtr);
return NULL;
}
I think that it will be easy to understand what this function does..
Acquiring list of processes using doubly-linked list of EPROCESS structures.
So, we go further. Following step will be acquiring the list of processes by iterating through the doubly-linked list of EPROCESS structures. The list begins with a header - PsActiveProcessHead, therefore for correct enumeration of processes we need to find this not exported symbol. For this purpose we will use a fact that System process is the first process in the list of processes. While being in DriverEntry we need to obtain pointer to current process by using PsGetCurrentProcess (drivers loaded using SC Manager API or ZwLoadDriver are always loaded in a context of process System), and BLink at offset ActiveProcessLinks will point to PsActiveProcessHead. It looks like this:
Code:
To obtain a name of process, its Process Id and ParrentProcessId, we use offsets of those fields in structure EPROCESS (pIdOffset, ppIdOffset, NameOffset, ActPsLink). These offsets differ in various versions Windows, therefore their acquisition is done in separate function which you can see in a source code of program Process Hunter (in the appendix).
Any concealment of process by API interception method, will be revealed in the above-stated way. But if process is hidden by means of DKOM (Direct Kernel Object Manipulation)method, this way will not help because such processes are removed from the list of processes.
Acquiring the list of processes using lists of threads in the scheduler.
One of methods of detection of such concealment (kao - the original text is ambiguous. Author probably meant "detection of processes hidden using DKOM method") consists in obtaining the list of processes from list of threads in the scheduler. There are three doubly-linked lists of threads (KiWaitInListHead, KiWaitOutListHead, KiDispatcherReadyListHead) available in Windows 2000. Former two lists contain threads waiting for certain events, and the latter contains threads ready for execution. When processing these lists and substracting offset of the thread list in structure ETHREAD, we will obtain pointer to ETHREAD of a thread (kao - this sentence is very hard to understand in original. I hope I got it right). This structure contains several pointers to the process related to this stream, namely - struct _KPROCESS *Process (0x44, 0x150) and struct _EPROCESS *ThreadsProcess (0x22C, offsets are specified for Windows 2000). First two pointers do not have any influence on functionality of a thread, and therefore can be easily modified to hide a process. On the contrary, third pointer is used by the scheduler when switching address spaces, therefore it cannot be changed. We shall use it to recognize which process owns a thread.
This detection method is used in the program klister, whose main disadvantage is that it works only under Windows 2000 (it fails to work with certain Service Packs, though). Such problem is caused by fact that Klister uses hardcoded addresses of thread lists, but these addresses are different in all Service Packs.
Hardcoding addresses in the program is poor solution as it makes software useless when new OS updates are released and makes it possible to avoid this detection method. Therefore it is necessary to search for list addresses dynamically, by analysing code of kernel functions in which these lists are used.
For the beginning we shall try to find KiWaitItListHead and KiWaitOutListHead in Windows 2000. Addresses of these lists are used in function KeWaitForSingleObject in the following code:
Code:
.text:0042DE56 mov ecx, offset KiWaitInListHead
.text:0042DE5B test al, al
.text:0042DE5D jz short loc_42DE6E
.text:0042DE5F cmp byte ptr [esi+135h], 0
.text:0042DE66 jz short loc_42DE6E
.text:0042DE68 cmp byte ptr [esi+33h], 19h
.text:0042DE6C jl short loc_42DE73
.text:0042DE6E mov ecx, offset KiWaitOutListHead
To obtain these addresses we should use length-disassembler (we shall use LDasm written by me) on KeWaitForSingleObject function. When the index (pOpcode) will point to a command "mov ecx, KiWaitInListHead", (pOpcode + 5) will point to "test al, al", and (pOpcode + 24) - to "mov ecx, KiWaitOutListHead". After that we can obtain KiWaitItListHead and KiWaitOutListHead addresses from (pOpcode + 1) and (pOpcode + 25) accordingly. The code which searches for these addresses looks like this:
Code:
void Win2KGetKiWaitInOutListHeads()
{
PUCHAR cPtr, pOpcode;
ULONG Length;
Unfortunately, Windows XP kernel differs very much from Windows 2000 kernel. The scheduler in XP does not have three, but only two lists of threads: KiWaitListHead and KiDispatcherReadyListHead. It is possible to find KiWaitListHead by scanning function KeDelayExecutionThread for the following code:
Code:
The most difficult problem is to find KiDispatcherReadyListHead. A problem lies infact that KiDispatcherReadyListHead address is not present in any of exported functions. Therefore it is necessary to use more complicated search algorithm for its calculation. We shall start our search from function KiDispatchInterrupt and there is only one place of interest in it containing a following code:
Code:
The First call in this code points to function in which there is a reference to KiDispatcherReadyListHead. However, search for the KiDispatcherReadyListHead address becomes more complicated because the relevant code in this function is different in Windows XP SP1 and SP2. In SP2 it looks like this:
Code:
Search for only one instruction "lea" is unreliable, therefore we shall check also that after "lea" command there is a command with rel32 displacement (function IsRelativeCmd in LDasm). The full code that searches for KiDispatcherReadyListHead will look like this:
Code:
void XPGetKiDispatcherReadyListHead()
{
PUCHAR cPtr, pOpcode;
PUCHAR CallAddr = NULL;
ULONG Length;
CollectProcess is a utility function that adds process to the list, if it is not there yet.
Acquiring the list of processes by intercepting system calls.
Any working process cooperates with system through API, and the majority of these inquiries turn into references to a kernel through the interface of system calls. Certainly, process can exist without using any API calls, but then it cannot carry out any useful (or harmful) deed. In general, the idea consists in intercepting system calls by using our handler, and obtaining pointer to EPROCESS of current process in our handler. The list of pointers shall be collected during collect certain period of time, and it will not include processes that did not carry out any system calls while this information was gathered (for example, processes whose threads are in a waiting state).
Interrupt 2Eh is used to make a system call in windows 2000, therefore we need to change a descriptor of corresponding interrupt in idt to intercept system calls. For this purpose we need to detect location of idt in memory by using sidt command. This command returns following structure:
Code:
The code for changing interrupt vector 2Eh will look like this:
Code:
void Set2kSyscallHook()
{
TIdt Idt;
__asm
{
pushad
cli
sidt [Idt]
mov esi, NewSyscall
mov ebx, Idt.Base
xchg [ebx + 0x170], si
rol esi, 0x10
xchg [ebx + 0x176], si
ror esi, 0x10
mov OldSyscall, esi
sti
popad
}
}
Of course it is necessary to restore everything before unloading the driver:
Code:
void Win2kSyscallUnhook()
{
TIdt Idt;
__asm
{
pushad
cli
sidt [Idt]
mov esi, OldSyscall
mov ebx, Idt.Base
mov [ebx + 0x170], si
rol esi, 0x10
mov [ebx + 0x176], si
sti
xor eax, eax
mov OldSyscall, eax
popad
}
}
Windows XP uses commands sysenter/sysexit (which have appeared in processors Pentium 2) to perform system calls. Functionality of these commands is controlled by model-specific registers (MSR). Address of a system call handler is set in MSR register SYSENTER_EIP_MSR (number 0x176). Reading MSR of the register is carried out by rdmsr command, and we need to set ECX = number of the register to be read, and the result is located in pair of registers EDX:EAX. In our case, SYSENTER_EIP_MSR register is 32 bit register, therefore EDX will be 0, and EAX will contain address of system call handler. Similarly, we can write into MSR register by using wrmsr instruction. There is one thing to note: when writing into 32-bit MSR register, EDX should be nulled, otherwise it will cause exceptions and will lead to immediate crash of system.
By taking all this into account, the code replacing system call handler will look like this:
Code:
One more Windows XP feature is that system call can be made both through sysenter, and through int 2Eh, therefore we need to replace both handlers with ours.
Our new system call handler should obtain pointer to EPROCESS of the current process and if it is new process, it should add this process into our list.
Accordingly, new system call handler will look like this:
Code:
To obtain full list of processes this code should work for some period of time and therefore we have the following problem: if process contained in the list will be removed, at the subsequent iteration through the list we will obtain invalid pointer, as a result we will either falsely detect a hidden process or will generate BSOD. The solution to this situation is - using PsSetCreateProcessNotifyRoutine to register our Callback function which will be called when creating or terminating a process. When process is being terminated, it should be deleted from our list. Callback function has the following prototype:
Code:
VOID
(*PCREATE_PROCESS_NOTIFY_ROUTINE) (
IN HANDLE ParentId,
IN HANDLE ProcessId,
IN BOOLEAN Create
);
Installation of callback routine is performed like this:
Code:
Here is one problem, Callback function is always called in a context of process to be terminated, hence it is impossible to delete process from lists directly in this callback function. For this purpose we shall use system work items, first we shall allocate memory for a work item by using IoAllocateWorkItem, and then we shall place the task in queue of a working thread by using of IoQueueWorkItem (kao - not sure about this sentence.. ). In handler procedure we will not only delete terminated processes from the list but also will add freshly created processes. Here is a code for handler:
Code:
This is rather reliable way of hidden process detection, as no process can manage without system calls, but some processes can be in a waiting state for a long time and will not carry out system calls during long period of time. Such processes will not be detected.
If desired, it is easy to bypass this method of detection. For this purpose it is necessary to change a method of performing system calls in hidden processes (redirect to another interrupt or callgate in GDT). It is especially easy to do so in Windows XP as it is enough to patch KiFastSystemCall in ntdll.dll and to create a corresponding gate for a system call. In Windows 2000 it is a little bit more difficult, as calls to int 2E are scattered throughout ntdll, but it is not so complex to find and patch all these places too, therefore it is not smart to rely on results of this check.
Acquiring the list of processes by iterating through handle table list.
If you have ever tried to hide process by removing it from list of PsActiveProcesses, perhaps you have noticed that when you enumerate handles by using ZwQuerySystemInformation, handles of hidden process are also enumerated and it is possible to detect their ProcessId. It is because for convenience of handle enumaration, all handle tables are incorporated in doubly-linked list HandleTableList. Offset of this list in HANDLE_TABLE structure for Windows 2000 is equal 0x054, and for Windows XP - 0x01C, this list with begins HandleTableListHead. HANDLE_TABLE structure contains pointer to process owning it (QuotaProcess), offset of this pointer in Windows 2000 is equal 0x00C, and in Windows XP - 0x004. By iterating through the list of handle tables we can build process list.
First we need to find HandleTableListHead. Kernel disassembly has shown that references to it are located deeply in the functions, therefore code disassembly method which we used earlier, cannot be used here. To find HandleTableListHead it is possible to use fact that HandleTableListHead is a global kernel variable and therefore it is located in one of kernel file sections and all other elements of HandleTableList are located in dynamically allocated memory and consequently always will be behind kernel address space limits. From this follows, that we need to acquire pointer to HandleTable of any process, and to iterate through linked-list until we find an element that is located in the kernel address space. This element will be HandleTableListHead.
To calculate imagebase and size of system kernel we will use ZwQuerySystemInformation with class SystemModuleInformation. It will return a table of descriptors for all loaded modules and first element always is "system". Taking into account all aforementioned, code that searches for HandleTableListHead looks like this:
This code is rather universal as it works in any Windows NT version, and can be applied not only to search for HandleTableListHead, but also for any other lists having similar structure.
After acquiring address of HandleTableListHead we can traverse through handle tables and construct list of processes based on this information:
Code:
This method of detection is used in F-Secure Black Light and in the last version KProcCheck. I think you will easily find a way to fool this detection method.
Acquiring list of processes by scanning PspCidTable.
There is one interesting thing to note - if process is removed from PsActiveProcesses list, it does not prevent opening process by using a call to OpenProcess. There is a method of hidden process detection that tries to detect processes by bruteforcing Pid and calling OpenProcess. I am not present this method, as it does not have any advantages, I would even say that it is "through-the-ass" method. But the fact of its existence means that in system there is one more list of processes besides PsActiveProcesses which is used by OpenProcess. When bruteforcing ProcessId we will certainly note that one process can be opened using a several different Pid, and it suggests that the second list of processes is something like HANDLE_TABLE. To verify this guess, we shall glance in function ZwOpenProcess:
Code:
As you see, this code copies given pointers in the safe way, checking if they point to user addresses, checks access rights and presence of the privilege "SeDebugPrivilege", then extracts ProcessId from CLIENT_ID structure and passes it to PsLookupProcessByProcessId function whose purpose is to obtain EPROCESS based on ProcessId. Remaining part of function is useless to us, therefore we should glance in PsLookupProcessByProcessId now:
Code:
PAGE:0049D725 public PsLookupProcessByProcessId
PAGE:0049D725 PsLookupProcessByProcessId proc near
PAGE:0049D725
PAGE:0049D725
PAGE:0049D725 ProcessId = dword ptr 8
PAGE:0049D725 Process = dword ptr 0Ch
PAGE:0049D725
PAGE:0049D725 mov edi, edi
PAGE:0049D727 push ebp
PAGE:0049D728 mov ebp, esp
PAGE:0049D72A push ebx
PAGE:0049D72B push esi
PAGE:0049D72C mov eax, large fs:124h
PAGE:0049D732 push [ebp+ProcessId]
PAGE:0049D735 mov esi, eax
PAGE:0049D737 dec dword ptr [esi+0D4h]
PAGE:0049D73D push PspCidTable
PAGE:0049D743 call ExMapHandleToPointer
PAGE:0049D748 mov ebx, eax
PAGE:0049D74A test ebx, ebx
PAGE:0049D74C mov [ebp+ProcessId], STATUS_INVALID_PARAMETER
PAGE:0049D753 jz short loc_49D787
PAGE:0049D755 push edi
PAGE:0049D756 mov edi, [ebx]
PAGE:0049D758 cmp byte ptr [edi], 3
PAGE:0049D75B jnz short loc_49D77A
PAGE:0049D75D cmp dword ptr [edi+1A4h], 0
PAGE:0049D764 jz short loc_49D77A
PAGE:0049D766 mov ecx, edi
PAGE:0049D768 call sub_4134A9
PAGE:0049D76D test al, al
PAGE:0049D76F jz short loc_49D77A
PAGE:0049D771 mov eax, [ebp+Process]
PAGE:0049D774 and [ebp+ProcessId], 0
PAGE:0049D778 mov [eax], edi
PAGE:0049D77A loc_49D77A:
PAGE:0049D77A push ebx
PAGE:0049D77B push PspCidTable
PAGE:0049D781 call ExUnlockHandleTableEntry
PAGE:0049D786 pop edi
PAGE:0049D787 loc_49D787:
PAGE:0049D787 inc dword ptr [esi+0D4h]
PAGE:0049D78D jnz short loc_49D79A
PAGE:0049D78F lea eax, [esi+34h]
PAGE:0049D792 cmp [eax], eax
PAGE:0049D794 jnz loc_52388A
PAGE:0049D79A loc_49D79A:
PAGE:0049D79A mov eax, [ebp+ProcessId]
PAGE:0049D79D pop esi
PAGE:0049D79E pop ebx
PAGE:0049D79F pop ebp
PAGE:0049D7A0 retn 8
What we see here, confirms presence of the second table of the processes organized as HANDLE_TABLE. The table is called PspCidTable and contains lists of processes and threads, and is also being used in functions PsLookupProcessThreadByCid and PsLookupThreadByThreadId. As we can see, handle and pointer to handle table is passed to function ExMapHandleToPointer, which (if handle is valid) returns pointer to an element of the table describing given handle - HANDLE_TABLE_ENTRY. After we process ntoskrnl.pdb with PDBdump and dig through obtained log, it is possible to figure out the following:
Code:
struct _HANDLE_TABLE_ENTRY {
// static data ------------------------------------
// non-static data --------------------------------
/*<thisrel this+0x0>*/ /*|0x4|*/ void* Object;
/*<thisrel this+0x0>*/ /*|0x4|*/ unsigned long ObAttributes;
/*<thisrel this+0x0>*/ /*|0x4|*/ struct _HANDLE_TABLE_ENTRY_INFO* InfoTable;
/*<thisrel this+0x0>*/ /*|0x4|*/ unsigned long Value;
/*<thisrel this+0x4>*/ /*|0x4|*/ unsigned long GrantedAccess;
/*<thisrel this+0x4>*/ /*|0x2|*/ unsigned short GrantedAccessIndex;
/*<thisrel this+0x6>*/ /*|0x2|*/ unsigned short CreatorBackTraceIndex;
/*<thisrel this+0x4>*/ /*|0x4|*/ long NextFreeTableEntry;
};// <size 0x8>
We can recover HANDLE_TABLE_ENTRY structure from this:
Code:
union
{
union
{
ACCESS_MASK GrantedAccess;
struct
{
USHORT GrantedAccessIndex;
USHORT CreatorBackTraceIndex;
};
};
LONG NextFreeTableEntry;
};
} HANDLE_TABLE_ENTRY, *PHANDLE_TABLE_ENTRY;
What's the use of it? First of all, we are interested into contents of Object field, which is the sum of the pointer to object described by this handle and a usage flag of the given element of the table (I will explain this in more details a little bit later). Field GrantedAccess, which specifies permitted access rights to the object from this handle, is rather interesting. For example, it is possible to open a file for reading, modify field GrantedAccess and to write to this file. Such method can be used for reading/writing of files which may not be opened with required access rights (for example - files locked by another process). But we shall return to our problem - to obtain the list of processes by analyzing PspCidTable.
For this purpose we need to understand handle table format, in order to iterate through this list. There is a serious difference between Windows 2000 and Windows XP here. Handle table formats a significantly different and we should analyze each OS separately.
For the beginning we shall analyze handle table in Windows 2000 as it is much easier to understand this format. For the beginning we shall glance in a code of function ExMapHandleToPointer:
Code:
PAGE:00493285 ExMapHandleToPointer proc near
PAGE:00493285
PAGE:00493285
PAGE:00493285 HandleTable = dword ptr 8
PAGE:00493285 Handle = dword ptr 0Ch
PAGE:00493285
PAGE:00493285 push esi
PAGE:00493286 push [esp+Handle]
PAGE:0049328A push [esp+4+HandleTable]
PAGE:0049328E call ExpLookupHandleTableEntry
PAGE:00493293 mov esi, eax
PAGE:00493295 test esi, esi
PAGE:00493297 jz short loc_4932A9
PAGE:00493299 push esi
PAGE:0049329A push [esp+4+HandleTable]
PAGE:0049329E call ExLockHandleTableEntry
PAGE:004932A3 neg al
PAGE:004932A5 sbb eax, eax
PAGE:004932A7 and eax, esi
PAGE:004932A9 loc_4932A9:
PAGE:004932A9 pop esi
PAGE:004932AA retn 8
PAGE:004932AA ExMapHandleToPointer endp
Here we call ExMapHandleToPointer function which performs search on HANDLE_TABLE, and call ExLockHandleTableEntry which sets Lock Bit. To understand internals of handle table we should disassemble both these functions. We shall begin with ExpLookupHandleTableEntry:
Code:
PAGE:00493545 ExpLookupHandleTableEntry proc near
PAGE:00493545
PAGE:00493545
PAGE:00493545 HandleTable = dword ptr 0Ch
PAGE:00493545 Handle = dword ptr 10h
PAGE:00493545
PAGE:00493545 push esi
PAGE:00493546 push edi
PAGE:00493547 mov edi, [esp+Handle]
PAGE:0049354B mov eax, 0FFh
PAGE:00493550 mov ecx, edi
PAGE:00493552 mov edx, edi
PAGE:00493554 mov esi, edi
PAGE:00493556 shr ecx, 12h
PAGE:00493559 shr edx, 0Ah
PAGE:0049355C shr esi, 2
PAGE:0049355F and ecx, eax
PAGE:00493561 and edx, eax
PAGE:00493563 and esi, eax
PAGE:00493565 test edi, 0FC000000h
PAGE:0049356B jnz short loc_49358A
PAGE:0049356D mov eax, [esp+HandleTable]
PAGE:00493571 mov eax, [eax+8]
PAGE:00493574 mov ecx, [eax+ecx*4]
PAGE:00493577 test ecx, ecx
PAGE:00493579 jz short loc_49358A
PAGE:0049357B mov ecx, [ecx+edx*4]
PAGE:0049357E test ecx, ecx
PAGE:00493580 jz short loc_49358A
PAGE:00493582 lea eax, [ecx+esi*8]
PAGE:00493585 loc_493585:
PAGE:00493585 pop edi
PAGE:00493586 pop esi
PAGE:00493587 retn 8
PAGE:0049358A loc_49358A:
PAGE:0049358A xor eax, eax
PAGE:0049358C jmp short loc_493585
PAGE:0049358C ExpLookupHandleTableEntry endp
In addition to it, I shall show HANDLE_TABLE structure obtained from ntoskrnl.pdb:
Code:
Based on these data we can recover structure of the handle table:
Code:
typedef struct _WIN2K_HANDLE_TABLE
{
ULONG Flags;
LONG HandleCount;
PHANDLE_TABLE_ENTRY **Table;
PEPROCESS QuotaProcess;
HANDLE UniqueProcessId;
LONG FirstFreeTableEntry;
LONG NextIndexNeedingPool;
ERESOURCE HandleTableLock;
LIST_ENTRY HandleTableList;
KEVENT HandleContentionEvent;
} WIN2K_HANDLE_TABLE , *PWIN2K_HANDLE_TABLE ;
Considering all of the above it is obvious, that handle value consists of three parts which are indexes in the three-level table of objects. Now we shall look in function ExLockHandleTableEntry:
This code checks 31st bit in Object element of HANDLE_TABLE_ENTRY structure, sets it and, if it is set - waits for HandleContentionEvent in HANDLE_TABLE. For us only the fact of setting TABLE_ENTRY_LOCK_BIT in important, as it is a part of the object address, and if flag is not set, we shall obtain invalid address. Now that we have understood format of the handle table, it is possible to write a code that iterates through objects in the table:
Code:
void ScanWin2KHandleTable(PWIN2K_HANDLE_TABLE HandleTable)
{
int i, j, k;
PHANDLE_TABLE_ENTRY Entry;
for (i = 0; i < 0x100; i++)
{
if (HandleTable->Table[i])
{
for (j = 0; j < 0x100; j++)
{
if (HandleTable->Table[i][j])
{
for (k = 0; k < 0x100; k++)
{
Entry = &HandleTable->Table[i][j][k];
This code processes all objects in the table and calls ProcessObject function for each of them. ProcessObject detects object type and processes it in appropriate way. Here a code of this function:
if (ObjectHeader->Type == *PsProcessType) CollectProcess(Object);
if (ObjectHeader->Type == *PsThreadType) ThreadCollect(Object);
}
OK, we have understood table of objects in Windows 2000, now it is time to start analysis in Windows XP. We shall begin with disassembling ExpLookupHandleTableEntry function:
Code:
PAGE:0048D3C1 ExpLookupHandleTableEntry proc near
PAGE:0048D3C1
PAGE:0048D3C1
PAGE:0048D3C1 HandleTable = dword ptr 8
PAGE:0048D3C1 Handle = dword ptr 0Ch
PAGE:0048D3C1
PAGE:0048D3C1 mov edi, edi
PAGE:0048D3C3 push ebp
PAGE:0048D3C4 mov ebp, esp
PAGE:0048D3C6 and [ebp+Handle], 0FFFFFFFCh
PAGE:0048D3CA mov eax, [ebp+Handle]
PAGE:0048D3CD mov ecx, [ebp+HandleTable]
PAGE:0048D3D0 mov edx, [ebp+Handle]
PAGE:0048D3D3 shr eax, 2
PAGE:0048D3D6 cmp edx, [ecx+38h]
PAGE:0048D3D9 jnb loc_4958D6
PAGE:0048D3DF push esi
PAGE:0048D3E0 mov esi, [ecx]
PAGE:0048D3E2 mov ecx, esi
PAGE:0048D3E4 and ecx, 3 // ecx - table level
PAGE:0048D3E7 and esi, not 3 // esi - pointer to first table
PAGE:0048D3EA sub ecx, 0
PAGE:0048D3ED jnz loc_48DEA4
PAGE:0048D3F3 lea eax, [esi+eax*8]
PAGE:0048D3F6 loc_48D3F6:
PAGE:0048D3F6 pop esi
PAGE:0048D3F7 loc_48D3F7:
PAGE:0048D3F7 pop ebp
PAGE:0048D3F8 retn 8
PAGE:0048DEA4 loc_48DEA4:
PAGE:0048DEA4 dec ecx
PAGE:0048DEA5 mov ecx, eax
PAGE:0048DEA7 jnz loc_52F57A
PAGE:0048DEAD shr ecx, 9
PAGE:0048DEB0 mov ecx, [esi+ecx*4]
PAGE:0048DEB3 loc_48DEB3:
PAGE:0048DEB3 and eax, 1FFh
PAGE:0048DEB8 lea eax, [ecx+eax*8]
PAGE:0048DEBB jmp loc_48D3F6
PAGE:0052F57A loc_52F57A:
PAGE:0052F57A shr ecx, 13h
PAGE:0052F57D mov edx, ecx
PAGE:0052F57F mov ecx, [esi+ecx*4]
PAGE:0052F582 shl edx, 13h
PAGE:0052F585 sub eax, edx
PAGE:0052F587 mov edx, eax
PAGE:0052F589 shr edx, 9
PAGE:0052F58C mov ecx, [ecx+edx*4]
PAGE:0052F58F jmp loc_48DEB3
Now we shall look at structure HANDLE_TABLE from ntoskrnl.pdb:
Code:
From the code above, it is obvious that function ExpLookupHandleTableEntry gets TableCode value from HANDLE_TABLE structure and based on its two low-order bits, calculates number of levels of the table. The remaining bits are pointer to the first level table. Hence HANDLE_TABLE in Windows XP can have from one up to three levels, thus the size of the table at any level is equal 1FFh. When quantity of records in the table increases, the system can automatically increase a level count. It is obvious, that the table will have the second level when quantity of records exceeds 0x200, and the third level - at quantity greater 0x40000. It is not known whether the system reduces of number of levels to the table when freeing (kao - releasing?) objects, I did not notice such behaviour.
Function ExLockHandleTableEntry does not exist in Windows XP, therefore the code blocking an element of the table is located in function ExMapHandleToPointer. Lest disassemble this function and look what it does:
Code:
PAGE:0048F61E ExMapHandleToPointer proc near
PAGE:0048F61E
PAGE:0048F61E
PAGE:0048F61E var_8 = dword ptr -8
PAGE:0048F61E var_4 = dword ptr -4
PAGE:0048F61E HandleTable = dword ptr 8
PAGE:0048F61E Handle = dword ptr 0Ch
PAGE:0048F61E
PAGE:0048F61E mov edi, edi
PAGE:0048F620 push ebp
PAGE:0048F621 mov ebp, esp
PAGE:0048F623 push ecx
PAGE:0048F624 push ecx
PAGE:0048F625 push edi
PAGE:0048F626 mov edi, [ebp+Handle]
PAGE:0048F629 test di, 7FCh
PAGE:0048F62E jz loc_4A2A36
PAGE:0048F634 push ebx
PAGE:0048F635 push esi
PAGE:0048F636 push edi
PAGE:0048F637 push [ebp+HandleTable]
PAGE:0048F63A call ExpLookupHandleTableEntry
PAGE:0048F63F mov esi, eax
PAGE:0048F641 test esi, esi
PAGE:0048F643 jz loc_4A2711
PAGE:0048F649 mov [ebp+var_4], esi
PAGE:0048F64C loc_48F64C:
PAGE:0048F64C mov ebx, [esi]
PAGE:0048F64E test bl, 1
PAGE:0048F651 mov [ebp+var_8], ebx
PAGE:0048F654 jz loc_508844
PAGE:0048F65A lea eax, [ebx-1]
PAGE:0048F65D mov [ebp+Handle], eax
PAGE:0048F660 mov eax, [ebp+var_8]
PAGE:0048F663 mov ecx, [ebp+var_4]
PAGE:0048F666 mov edx, [ebp+Handle]
PAGE:0048F669 cmpxchg [ecx], edx
PAGE:0048F66C cmp eax, ebx
PAGE:0048F66E jnz loc_50884C
PAGE:0048F674 mov eax, esi
PAGE:0048F676 loc_48F676:
PAGE:0048F676 pop esi
PAGE:0048F677 pop ebx
PAGE:0048F678 loc_48F678:
PAGE:0048F678 pop edi
PAGE:0048F679 leave
PAGE:0048F67A retn 8
PAGE:0048F67A ExMapHandleToPointer endp
When ExpLookupHandleTableEntry function returns pointer to HANDLE_TABLE_ENTRY, we check low-order bit of Object field and, if it is set, it is cleared (kao - there is typo in original here... Hopefully I got it right...) and, if it is not set, we wait until it is set. Hence when obtaining the address of object we should not set the high-order bit (as in Windows 2000), but clear low-order bit. In view of the aforesaid, we can make a code that scans the table of objects:
Code:
void ScanXpHandleTable(PXP_HANDLE_TABLE HandleTable)
{
int i, j, k;
PHANDLE_TABLE_ENTRY Entry;
ULONG TableCode = HandleTable->TableCode & ~TABLE_LEVEL_MASK;
switch (HandleTable->TableCode & TABLE_LEVEL_MASK)
{
case 0 :
for (i = 0; i < 0x200; i++)
{
Entry = &((PHANDLE_TABLE_ENTRY)TableCode)[i];
if (Entry->Object) ProcessObject((PVOID)((ULONG)Entry->Object & ~XP_TABLE_ENTRY_LOCK_BIT));
}
break;
case 1 :
for (i = 0; i < 0x200; i++)
{
if (((PVOID *)TableCode)[i])
{
for (j = 0; j < 0x200; j++)
{
Entry = &((PHANDLE_TABLE_ENTRY *)TableCode)[i][j];
if (Entry->Object) ProcessObject((PVOID)((ULONG)Entry->Object & ~XP_TABLE_ENTRY_LOCK_BIT));
}
}
}
break;
case 2 :
for (i = 0; i < 0x200; i++)
{
if (((PVOID *)TableCode)[i])
{
for (j = 0; j < 0x200; j++)
{
if (((PVOID **)TableCode)[i][j])
{
for (k = 0; k < 0x200; k++)
{
Entry = &((PHANDLE_TABLE_ENTRY **)TableCode)[i][j][k];
So we have understood format of object tables. Now to enumerate processes we need to obtain PspCidTable address. As you have probably guessed, we shall search for it in function PsLookupProcessByProcessId, first call in it will contain PspCidTable address. Here a code:
Code:
void GetPspCidTable()
{
PUCHAR cPtr, pOpcode;
ULONG Length;
Now we know how to process PspCidTable. It is easily possible to view all objects in tables of all processes in a similar fashion, and to analyze objects which belong to hidden processes, in the same way as we did in UserMode. If you have understood with all aforementioned, I think you can do it.
Translation of hxxp://wasm.ru/article.php?article=hiddndt I was unable to find any policy about article translations on
wasm.ru. If admins of wasm.ru or author feels that some rights were violated, please let me or board admins know and this translation will be removed promptly.
这篇翻译是来自 hxxp://wasm.ru/article.php?article=hiddndt,我没有得到wasm.ru关于翻译这篇文章的许可。因此,如果wasm.ru的管理员
或者作者认为权利得到侵犯,请告诉我,或者告诉斑竹,这篇文章会快速的删除掉
My apologies for rather crude English language, both English and Russian are not my native languages. If anyone wishes to correct some grammatical or factual mistakes, he is welcome to do so.
英语和俄语都不是我的母语,因此对我糟糕的英语水平表示歉意。如果有人愿意指出其中的语法错误,我非常欢迎。
Source codes will not be translated. They are available at the original site.
源代码没有翻译,原来网站有下载。
Many users have got used that Windows NT Task Manager shows all processes, and many consider that it is impossible to hide a process from Task Manager. Actually, process hiding is incredibly simple. There are lots of methods available for such a purpose and there are source codes available. It still amazes me that there are only a few trojans using these methods. Literally only 1 trojan from a 1000 is hidden. I think that trojan authors are lazy, since it requires extra work to hide the process and it is always easier to use ready-made sources and copy-paste them. Therefore we should expect hidden trojan processes in a near future.
许多人已经习惯使用Windows NT的任务管理器查看所有进程,并且许多人认为从任务管理器中隐藏一个进程是不可能的。事实上,隐藏进程是
不能相信的简单。有许多方法可以完成这一目的并且有许多可以参考的代码。使我吃惊的是仅有一小部分的特洛伊木马使用了这一方法。
也许1000个当中只有1个吧。我想是特洛伊木马的作者比较懒吧,因为这需要额外的工作去隐藏进程,并且要使用现成的代码和拷贝-粘贴它们
因此在不久的将来隐藏特洛伊木马的进程值得期待。
Naturally, it is necessary to have protection against hidden processes. Manufacturers of antiviruses and firewals lagging behind as their products are not able to find hidden processes. For this purpose there are only a few utilities from which free-of-charge is only Klister (works only on Windows 2000). All other companies demand considerable money (kao - not true. BlackLight Beta from FSecure is free.). Furthermore, all these utilities can be easily avoided.
当然了,查到隐藏的进程也是非常有必要的。杀毒软件和防火墙软件滞后于病毒和木马,不能找到隐藏进程。由于这种原因只有一个免费工具
是Klister(只能用在WIN2000)其他公司都要求付费。(靠 - 不是真的. BlackLight Beta from FSecure 是免费的.)
All programs available now, use one method for hidden process detection, therefore we have 2 choices:
* think up a method of concealment from a certain principle of detection,
* think up a method of concealment from a certain program, which is much easier.
这里所有的程序都是可用的,用一种方法进行隐藏进程的探测,这里我们有两种选择:
*从一个现有的检测原理出发建立隐藏的方法
*从一个现有程序出发建立隐藏方法,非常容易
The user who bought the commercial program cannot change it, and therefore the binding to the concrete program works reliably enough. Therefore the latter method is used in commercial rootkits (for example hxdef Golden edition). The only solution is creation free-of-charge Opensource program for detection of hidden processes. Such program shall employ several detection methods, and therefore would defeat programs concealed from one certain method. Each user can protect against binding to a certain program, it is necessary to take source codes of the program and to alter them to his own liking.
用户买了商业软件不能改变它,并且捆绑在一起的程序运行是足够的稳定。因此后者的方法是商业软件的基础(例如 hxdef Golden edition)
唯一的解决方法是制造免费的并且代码公开的检测隐藏进程的程序。这样的程序需要几种探测方法,这样才能是隐藏进程能被找到。每一个用户都可以保护不被绑定软件。修改源代码是它适合自己也是必要的。
In this article I will discuss the basic methods of detection of hidden processes, show examples of a code using these methods, and to create working program for detection of hidden processes which would meet all above-stated requirements.
在这篇文章中我将讨论基本的探测隐藏进程的方法,例子的源代码使用了这些方法,创建可以运行检测隐藏进程的程序将遇到所有上面阐述的要求。
Detection in User Mode (ring3)
在用户级检测(ring3)
For the beginning we shall consider simple methods of detection which can be applied in 3 ring, without use of drivers. They are based on fact, that each process generates certain traces of the activity. Based on these traces we can detect hidden process. Such traces include handles opened by process, windows and created system objects. It is simple to avoid from such detection techniques, but for this purpose it is necessary to consider ALL traces left by process. Such stealth mode is not realized in any of public rootkits (unfortunately private versions are not available to me). Usermode methods are simple in implementation, safe to use, and can give a positive effect, therefore their usage should not be neglected.
作为开始我们将考虑在Ring3级检测的简单方法,没有使用驱动。它们建立在事实上,每一个进程都生成一个动作的跟踪。依靠这种跟踪我们可以检测隐藏进程。这种跟踪包括进程打开的句柄,窗口和创建的系统对象。避免这样的检测技术也是非常的简单,但是为了探测进程考虑进程留下的跟踪是必要的。这种秘密模式在许多公共控件中没有实现(不幸的是个人版本中也不是有效的)。用户模式在运行中是简单,安全的能给出正面的效果,因此这种方法的应用不应该被忽略。
For the beginning we shall be define data returned by search function, let it be linked lists:
开始需要定义通过搜索函数返回的数据,如下:
Code:
type
PProcList = ^TProcList;
TProcList = packed record
NextItem: pointer;
ProcName: array [0..MAX_PATH] of Char;
ProcId: dword;
ParrentId: dword;
end;
Acquiring the list of processes by using ToolHelp API
通过使用ToolHelp API函数获取进程的列表
We shall define reference function receiving the list of processes, we shall compare these results to results obtained by all 我们将定义参考程序接收进程的列表,与通过其它方法得到的结果进行比较。
other means:
其它方法:
Code:
{通过使用ToolHelp API函数获取进程的列表
Acquiring list of processes by using ToolHelp API.
}
procedure GetToolHelpProcessList(var List: PListStruct);
var
Snap: dword;
Process: TPROCESSENTRY32;
NewItem: PProcessRecord;
begin
Snap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if Snap <> INVALID_HANDLE_VALUE then
begin
Process.dwSize := SizeOf(TPROCESSENTRY32);
if Process32First(Snap, Process) then
repeat
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
NewItem^.ProcessId := Process.th32ProcessID;
NewItem^.ParrentPID := Process.th32ParentProcessID;
lstrcpy(@NewItem^.ProcessName, Process.szExeFile);
AddItem(List, NewItem);
until not Process32Next(Snap, Process);
CloseHandle(Snap);
end;
end;
It is obvious that any hidden process will not be found, therefore this function will be used as a reference for hidden process detection.
很明显没有发现任何隐藏进程,因此这个函数将用作探测隐藏进程的一个参考函数。
Acquiring the list of processes by using Native API
通过使用Native API函数获取进程的列表
The next scanning level will be acquisition a list of processes through ZwQuerySystemInformation (Native API). It is improbable that something will be found out at this level but we should check it anyway.
下面的扫描将通过使用ZwQuerySystemInformation (Native API)函数获得进程的列表。在这一级别一些进程被发现是不大可能的但是我们应该对它进行检测。
Code:
{通过使用ZwQuerySystemInformation (Native API)函数获得进程的列表
Acquiring list of processes by using ZwQuerySystemInformation.
}
procedure GetNativeProcessList(var List: PListStruct);
var
Info: PSYSTEM_PROCESSES;
NewItem: PProcessRecord;
Mem: pointer;
begin
Info := GetInfoTable(SystemProcessesAndThreadsInformation);
Mem := Info;
if Info = nil then Exit;
repeat
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
lstrcpy(@NewItem^.ProcessName,
PChar(WideCharToString(Info^.ProcessName.Buffer)));
NewItem^.ProcessId := Info^.ProcessId;
NewItem^.ParrentPID := Info^.InheritedFromProcessId;
AddItem(List, NewItem);
Info := pointer(dword(info) + info^.NextEntryDelta);
until Info^.NextEntryDelta = 0;
VirtualFree(Mem, 0, MEM_RELEASE);
end;
Acquiring the list of processes by using list of opened handles.
通过使用打开的句柄来获得进程列表。
Many hidden processes do not hide handles opened by them, hence we can construct the list of processes by enumerating opened handles using ZwQuerySystemInformation.
许多隐藏进程不隐藏自己打开的句柄,因此我们能通过枚举打开的句柄构建进程的列表通过使用ZwQuerySystemInformation函数。
Code:
{通过使用打开的句柄来获得进程列表。
Acquiring the list of processes by using list of opened handles.
Returns only ProcessId.
}
procedure GetHandlesProcessList(var List: PListStruct);
var
Info: PSYSTEM_HANDLE_INFORMATION_EX;
NewItem: PProcessRecord;
r: dword;
OldPid: dword;
begin
OldPid := 0;
Info := GetInfoTable(SystemHandleInformation);
if Info = nil then Exit;
for r := 0 to Info^.NumberOfHandles do
if Info^.Information[r].ProcessId <> OldPid then
begin
OldPid := Info^.Information[r].ProcessId;
GetMem(NewItem, SizeOf(TProcessRecord));
ZeroMemory(NewItem, SizeOf(TProcessRecord));
NewItem^.ProcessId := OldPid;
AddItem(List, NewItem);
end;
VirtualFree(Info, 0, MEM_RELEASE);
end;