SUPR3HardenedMain-win.cpp revision 3e8dfb3b094ad264c36cbb8d513bf6753b729c90
/* $Id$ */
/** @file
* VirtualBox Support Library - Hardened main(), windows bits.
*/
/*
* Copyright (C) 2006-2014 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <AccCtrl.h>
#include <AclApi.h>
#ifndef PROCESS_SET_LIMITED_INFORMATION
# define PROCESS_SET_LIMITED_INFORMATION 0x2000
#endif
# define LOAD_LIBRARY_SEARCH_APPLICATION_DIR 0x200
# define LOAD_LIBRARY_SEARCH_SYSTEM32 0x800
#endif
#include <iprt/initterm.h>
#include "SUPLibInternal.h"
#include "win/SUPHardenedVerify-win.h"
#include "../SUPDrvIOC.h"
#ifndef IMAGE_SCN_TYPE_NOLOAD
# define IMAGE_SCN_TYPE_NOLOAD 0x00000002
#endif
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/** The first argument of a respawed stub when respawned for the first time.
* This just needs to be unique enough to avoid most confusion with real
* executable names, there are other checks in place to make sure we've respanwed. */
#define SUPR3_RESPAWN_1_ARG0 "60eaff78-4bdd-042d-2e72-669728efd737-suplib-2ndchild"
/** The first argument of a respawed stub when respawned for the second time.
* This just needs to be unique enough to avoid most confusion with real
* executable names, there are other checks in place to make sure we've respanwed. */
#define SUPR3_RESPAWN_2_ARG0 "60eaff78-4bdd-042d-2e72-669728efd737-suplib-3rdchild"
/** Unconditional assertion. */
#define SUPR3HARDENED_ASSERT(a_Expr) \
do { \
if (!(a_Expr)) \
} while (0)
/** Unconditional assertion of NT_SUCCESS. */
#define SUPR3HARDENED_ASSERT_NT_SUCCESS(a_Expr) \
do { \
if (!NT_SUCCESS(rcNtAssert)) \
} while (0)
/** Unconditional assertion of a WIN32 API returning non-FALSE. */
#define SUPR3HARDENED_ASSERT_WIN32_SUCCESS(a_Expr) \
do { \
} while (0)
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/**
* Security descriptor cleanup structure.
*/
typedef struct MYSECURITYCLEANUP
{
union
{
union
{
} Acl;
/** Pointer to security cleanup structure. */
typedef MYSECURITYCLEANUP *PMYSECURITYCLEANUP;
/**
* Image verifier cache entry.
*/
typedef struct VERIFIERCACHEENTRY
{
/** Pointer to the next entry with the same hash value. */
struct VERIFIERCACHEENTRY * volatile pNext;
/** Next entry in the WinVerifyTrust todo list. */
struct VERIFIERCACHEENTRY * volatile pNextTodoWvt;
/** The file handle. */
/** If fIndexNumber is set, this is an file system internal file identifier. */
/** The path hash value. */
/** The verification result. */
int rc;
/** Used for shutting up errors after a while. */
uint32_t volatile cErrorHits;
/** The validation flags (for WinVerifyTrust retry). */
/** Whether IndexNumber is valid */
bool fIndexNumberValid;
/** Whether verified by WinVerifyTrust. */
bool volatile fWinVerifyTrust;
/** cwcPath * sizeof(RTUTF16). */
/** The full path of this entry (variable size). */
/** Pointer to an image verifier path entry. */
typedef VERIFIERCACHEENTRY *PVERIFIERCACHEENTRY;
/**
* Name of an import DLL that we need to check out.
*/
typedef struct VERIFIERCACHEIMPORT
{
/** Pointer to the next DLL in the list. */
struct VERIFIERCACHEIMPORT * volatile pNext;
/** The length of pwszAltSearchDir if available. */
/** This points the directory containing the DLL needing it, this will be
* NULL for a System32 DLL. */
/** The name of the import DLL (variable length). */
char szName[1];
/** Pointer to a import DLL that needs checking out. */
typedef VERIFIERCACHEIMPORT *PVERIFIERCACHEIMPORT;
/**
* Child requests.
*/
typedef enum SUPR3WINCHILDREQ
{
/** Perform child purification and close full access handles (must be zero). */
/** Close the events, we're good on our own from here on. */
/** Reporting error. */
/** End of valid requests. */
/**
* Child process parameters.
*/
typedef struct SUPR3WINPROCPARAMS
{
/** The event semaphore the child will be waiting on. */
/** The event semaphore the parent will be waiting on. */
/** The address of the NTDLL. This is only valid during the very early
* initialization as we abuse for thread creation protection. */
/** The requested operation (set by the child). */
/** The last status. */
/** The init operation the error relates to if message, kSupInitOp_Invalid if
* not message. */
/** Where if message. */
char szWhere[80];
/** Error message / path name string space. */
char szErrorMsg[4096];
/**
* Child process data structure for use during child process init setup and
* purification.
*/
typedef struct SUPR3HARDNTCHILD
{
/** Process handle. */
/** Primary thread handle. */
/** Handle to the parent process, if we're the middle (stub) process. */
/** The event semaphore the child will be waiting on. */
/** The event semaphore the parent will be waiting on. */
/** The address of NTDLL in the child. */
/** The address of NTDLL in this process. */
/** Which respawn number this is (1 = stub, 2 = VM). */
int iWhich;
/** The basic process info. */
/** The probable size of the PEB. */
/** The pristine process environment block. */
/** The child process parameters. */
/** Pointer to a child process data structure. */
typedef SUPR3HARDNTCHILD *PSUPR3HARDNTCHILD;
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/** Process parameters. Specified by parent if VM process, see
* supR3HardenedVmProcessInit. */
/** Set if supR3HardenedEarlyProcessInit was invoked. */
bool g_fSupEarlyProcessInit = false;
/** Set if the stub device has been opened (stub process only). */
bool g_fSupStubOpened = false;
/** @name Global variables initialized by suplibHardenedWindowsMain.
* @{ */
/** Combined windows NT version number. See SUP_MAKE_NT_VER_COMBINED. */
uint32_t g_uNtVerCombined = 0;
/** Count calls to the special main function for linking santity checks. */
static uint32_t volatile g_cSuplibHardenedWindowsMainCalls;
/** The UTF-16 windows path to the executable. */
/** The NT path of the executable. */
/** The offset into g_SupLibHardenedExeNtPath of the executable name (WCHAR,
* not byte). This also gives the length of the exectuable directory path,
* including a trailing slash. */
/** @} */
/** @name Hook related variables.
* @{ */
/** Pointer to the bit of assembly code that will perform the original
* NtCreateSection operation. */
/** Pointer to the NtCreateSection function in NtDll (for patching purposes). */
static uint8_t *g_pbNtCreateSection;
/** The patched NtCreateSection bytes (for restoring). */
/** Pointer to the bit of assembly code that will perform the original
* LdrLoadDll operation. */
/** Pointer to the LdrLoadDll function in NtDll (for patching purposes). */
static uint8_t *g_pbLdrLoadDll;
/** The patched LdrLoadDll bytes (for restoring). */
/** The hash table of verifier cache . */
/** Queue of cached images which needs WinVerifyTrust to check them. */
/** Queue of cached images which needs their imports checked. */
/** The windows path to dir \\SystemRoot\\System32 directory (technically
* this whatever \KnownDlls\KnownDllPath points to). */
/** @ */
/** Positive if the DLL notification callback has been registered, counts
* registration attempts as negative. */
static int g_cDllNotificationRegistered = 0;
/** The registration cookie of the DLL notification callback. */
/** Static error info structure used during init. */
static RTERRINFOSTATIC g_ErrInfoStatic;
/** In the assembly file. */
/** Whether we've patched our own LdrInitializeThunk or not. We do this to
* disable thread creation. */
static bool g_fSupInitThunkSelfPatched;
/** The backup of our own LdrInitializeThunk code, for enabling and disabling
* thread creation in this process. */
/** Mask of adversaries that we've detected (SUPHARDNT_ADVERSARY_XXX). */
static uint32_t g_fSupAdversaries = 0;
/** @name SUPHARDNT_ADVERSARY_XXX - Adversaries
* @{ */
/** Symantec endpoint protection or similar including SysPlant.sys. */
#define SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT RT_BIT_32(0)
/** Symantec Norton 360. */
/** Avast! */
/** TrendMicro OfficeScan and probably others. */
/** McAfee. */
/** Kaspersky or OEMs of it. */
/** Malwarebytes Anti-Malware (MBAM). */
/** AVG Internet Security. */
/** Panda Security. */
/** Microsoft Security Essentials. */
/** Comodo. */
/** Check Point's Zone Alarm (may include Kaspersky). */
/** Unknown adversary detected while waiting on child. */
/** @} */
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
static NTSTATUS supR3HardenedScreenImage(HANDLE hFile, bool fImage, PULONG pfAccess, PULONG pfProtect,
bool *pfQuietFailure);
static void supR3HardenedWinRegisterDllNotificationCallback(void);
static void supR3HardenedWinReInstallHooks(bool fFirst);
DECLASM(void) supR3HardenedEarlyProcessInitThunk(void);
/**
* Simple wide char search routine.
*
* @returns Pointer to the first location of @a wcNeedle in @a pwszHaystack.
* NULL if not found.
* @param pwszHaystack Pointer to the string that should be searched.
* @param wcNeedle The character to search for.
*/
{
for (;;)
{
return (PRTUTF16)pwszHaystack;
if (wcCur == '\0')
return NULL;
pwszHaystack++;
}
}
/**
* Simple wide char string length routine.
*
* @returns The number of characters in the given string. (Excludes the
* terminator.)
* @param pwsz The string.
*/
{
while (*pwszCur != '\0')
pwszCur++;
}
/**
* Our version of GetTickCount.
* @returns Millisecond timestamp.
*/
static uint64_t supR3HardenedWinGetMilliTS(void)
{
/* use interrupt time */
do
{
}
/**
* Wrapper around LoadLibraryEx that deals with the UTF-8 to UTF-16 conversion
* and supplies the right flags.
*
* @returns Module handle on success, NULL on failure.
* @param pszName The full path to the DLL.
* @param fSystem32Only Whether to only look for imports in the system32
* directory. If set to false, the application
* directory is also searched.
*/
{
if (RT_SUCCESS(rc))
{
while (*pwszPath)
{
if (*pwszPath == '/')
*pwszPath = '\\';
pwszPath++;
}
{
if (!fSystem32Only)
}
/* Vista, W7, W2K8R might not work without KB2533623, so retry with no flags. */
if ( !pvRet
&& fFlags
return pvRet;
}
return NULL;
}
/**
* Gets the internal index number of the file.
*
* @returns True if we got an index number, false if not.
* @param hFile The file in question.
* @param pIndexNumber where to return the index number.
*/
{
NTSTATUS rcNt = NtQueryInformationFile(hFile, &Ios, pIndexNumber, sizeof(*pIndexNumber), FileInternalInformation);
if (NT_SUCCESS(rcNt))
#ifdef DEBUG_bird
if (!NT_SUCCESS(rcNt))
__debugbreak();
#endif
}
/**
* Calculates the hash value for the given UTF-16 path string.
*
* @returns Hash value.
* @param pUniStr String to hash.
*/
{
while (cwcLeft-- > 0)
{
if (wc < 0x80)
}
return uHash;
}
/**
* Calculates the hash value for a directory + filename combo as if they were
* one single string.
*
* @returns Hash value.
* @param pawcDir The directory name.
* @param cwcDir The length of the directory name. RTSTR_MAX if
* not available.
* @param pszName The import name (UTF-8).
*/
static uint32_t supR3HardenedWinVerifyCacheHashDirAndFile(PCRTUTF16 pawcDir, uint32_t cwcDir, const char *pszName)
{
while (cwcDir-- > 0)
{
if (wc < 0x80)
}
unsigned char ch = '\\';
{
}
return uHash;
}
/**
* Verify string cache compare function.
*
* @returns true if the strings match, false if not.
* @param pawcLeft The left hand string.
* @param pawcRight The right hand string.
* @param cwcToCompare The number of chars to compare.
*/
static bool supR3HardenedWinVerifyCacheIsMatch(PCRTUTF16 pawcLeft, PCRTUTF16 pawcRight, uint32_t cwcToCompare)
{
/* Try a quick memory compare first. */
return true;
/* Slow char by char compare. */
while (cwcToCompare-- > 0)
{
{
return false;
}
}
return true;
}
/**
* Inserts the given verifier result into the cache.
*
* @param pUniStr The full path of the image.
* @param hFile The file handle - must either be entered into
* the cache or closed.
* @param rc The verifier result.
* @param fWinVerifyTrust Whether verified by WinVerifyTrust or not.
* @param fFlags The image verification flags.
*/
{
/*
* Allocate and initalize a new entry.
*/
PVERIFIERCACHEENTRY pEntry = (PVERIFIERCACHEENTRY)RTMemAllocZ(sizeof(VERIFIERCACHEENTRY) + pUniStr->Length);
if (pEntry)
{
pEntry->cErrorHits = 0;
/*
* Try insert it, careful with concurrent code as well as potential duplicates.
*/
for (;;)
{
{
if (!fWinVerifyTrust)
do
return;
}
if (!pOther)
continue;
&& supR3HardenedWinVerifyCacheIsMatch(pOther->wszPath, pEntry->wszPath, pEntry->cbPath / sizeof(RTUTF16)))
break;
}
/* Duplicate entry (may happen due to races). */
}
}
/**
* Looks up an entry in the verifier hash table.
*
* @return Pointer to the entry on if found, NULL if not.
* @param pUniStr The full path of the image.
* @param hFile The file handle.
*/
static PVERIFIERCACHEENTRY supR3HardenedWinVerifyCacheLookup(PCUNICODE_STRING pUniStr, HANDLE hFile)
{
while (pCur)
{
{
if (!pCur->fIndexNumberValid)
return pCur;
if ( fIndexNumberValid
return pCur;
#ifdef DEBUG_bird
__debugbreak();
#endif
}
}
return NULL;
}
/**
* Looks up an import DLL in the verifier hash table.
*
* @return Pointer to the entry on if found, NULL if not.
* @param pawcDir The directory name.
* @param cwcDir The length of the directory name.
* @param pszName The import name (UTF-8).
*/
static PVERIFIERCACHEENTRY supR3HardenedWinVerifyCacheLookupImport(PCRTUTF16 pawcDir, uint32_t cwcDir, const char *pszName)
{
while (pCur)
{
{
{
{
{
return pCur;
}
}
}
}
}
return NULL;
}
/**
* Schedules the import DLLs for verification and entry into the cache.
*
* @param hLdrMod The loader module which imports should be
* scheduled for verification.
* @param pwszName The full NT path of the module.
*/
{
/*
* Any imports?
*/
int rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_IMPORT_COUNT, NULL /*pvBits*/, &cImports, sizeof(cImports), NULL);
if (RT_SUCCESS(rc))
{
if (cImports)
{
/*
* Figure out the DLL directory from pwszName.
*/
uint32_t i = 0;
cwcDir = i - 1;
/*
* Enumerate the imports.
*/
for (i = 0; i < cImports; i++)
{
union
{
char szName[256];
} uBuf;
rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_IMPORT_MODULE, NULL /*pvBits*/, &uBuf, sizeof(uBuf), NULL);
if (RT_SUCCESS(rc))
{
/*
* Skip kernel32, ntdll and API set stuff.
*/
{
continue;
}
/*
* Skip to the next one if it's already in the cache.
*/
{
SUP_DPRINTF(("supR3HardenedWinVerifyCacheScheduleImports: '%s' cached for system32\n", uBuf.szName));
continue;
}
{
continue;
}
{
SUP_DPRINTF(("supR3HardenedWinVerifyCacheScheduleImports: '%s' cached for dll dir\n", uBuf.szName));
continue;
}
/* We could skip already scheduled modules, but that'll require serialization and extra work... */
/*
* Add it to the todo list.
*/
SUP_DPRINTF(("supR3HardenedWinVerifyCacheScheduleImports: Import todo: #%u '%s'.\n", i, uBuf.szName));
if (pImport)
{
/* Init it. */
if (!pawcDir)
{
pImport->cwcAltSearchDir = 0;
}
else
{
}
/* Insert it. */
do
}
}
else
}
}
else
}
else
}
/**
* Processes the list of import todos.
*/
static void supR3HardenedWinVerifyCacheProcessImportTodos(void)
{
/*
* Work until we've got nothing more todo.
*/
for (;;)
{
PVERIFIERCACHEIMPORT pTodo = ASMAtomicXchgPtrT(&g_pVerifierCacheTodoImports, NULL, PVERIFIERCACHEIMPORT);
if (!pTodo)
break;
do
{
/*
* Not in the cached already?
*/
&& ( pCur->cwcAltSearchDir == 0
|| !supR3HardenedWinVerifyCacheLookupImport(pCur->pwszAltSearchDir, pCur->cwcAltSearchDir, pCur->szName)) )
{
/*
* Try locate the imported DLL and open it.
*/
/*
* Check for DLL isolation / redirection / mapping.
*/
if (RT_SUCCESS(rc))
{
UniStrStatic.Length = 0;
NULL /*pNewFlags*/,
NULL /*pcbFilename*/,
NULL /*pcbNeeded*/);
if (NT_SUCCESS(rcNtRedir))
{
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
if (NT_SUCCESS(rcNt))
{
/* For accurate logging. */
}
else
}
}
else
SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: RTStrToUtf16Ex #1 failed: %Rrc\n", rc));
/*
* If not something that gets remapped, do the half normal searching we need.
*/
if (hFile == INVALID_HANDLE_VALUE)
{
struct
{
{
};
/* Search System32 first, unless it's a 'V*' or 'm*' name, the latter for msvcrt. */
{
}
{
{
if (RT_SUCCESS(rc))
{
InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
if (NT_SUCCESS(rcNt))
break;
}
else
SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: RTStrToUtf16Ex #2 failed: %Rrc\n", rc));
}
}
}
/*
* If we successfully opened it, verify it and cache the result.
*/
if (hFile != INVALID_HANDLE_VALUE)
{
SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: '%s' -> '%ls' [rcNtRedir=%#x]\n",
bool fCallRealApi = false;
}
else
SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: Failed to locate '%s'\n", pCur->szName));
}
else
SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: '%s' is in the cache.\n", pCur->szName));
} while (pTodo);
}
}
/**
* Processes the list of WinVerifyTrust todos.
*/
static void supR3HardenedWinVerifyCacheProcessWvtTodos(void)
{
/*
* Work until we've got nothing more todo.
*/
for (;;)
{
break;
if (!pTodo)
break;
do
{
if ( !pCur->fWinVerifyTrust
{
bool fWinVerifyTrust = false;
{
SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessWvtTodos: %d (was %d) fWinVerifyTrust=%d for '%ls'\n",
pCur->fWinVerifyTrust = true;
}
else
{
/* Retry it at a later time. */
SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessWvtTodos: %d (was %d) fWinVerifyTrust=%d for '%ls' [rescheduled]\n",
if (!pReschedule)
}
}
/* else: already processed. */
} while (pTodo);
}
/*
* Anything to reschedule.
*/
if (pReschedule)
{
do
}
}
/**
* Checks whether the path could be containing alternative 8.3 names generated
* by NTFS, FAT, or other similar file systems.
*
* @returns Pointer to the first component that might be an 8.3 name, NULL if
* not 8.3 path.
* @param pwszPath The path to check.
*/
{
for (;;)
{
if (wc == '~')
{
/* Could check more here before jumping to conclusions... */
}
else if (wc == 0)
break;
}
return NULL;
}
/**
* Fixes up a path possibly containing one or more alternative 8-dot-3 style
* components.
*
* The path is fixed up in place. Errors are ignored.
*
* @param hFile The handle to the file which path we're fixing up.
* @param pUniStr The path to fix up. MaximumLength is the max buffer
* length.
*/
{
/*
* We could use FileNormalizedNameInformation here and slap the volume device
* path in front of the result, but it's only supported since windows 8.0
* according to some docs... So we expand all supicious names.
*/
while (*pwszFix)
{
break;
pwszFixEnd++;
if (wc == '\0')
break;
InitializeObjectAttributes(&ObjAttr, &NtDir, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
{
union
{
} uBuf;
NULL /* Event */,
NULL /* ApcRoutine */,
NULL /* ApcContext */,
&Ios,
&uBuf,
FALSE /*ReturnSingleEntry*/,
FALSE /*RestartScan */);
if (NT_SUCCESS(rcNt) && uBuf.Info.NextEntryOffset == 0) /* There shall only be one entry matching... */
{
while (offName > 0 && uBuf.Info.FileName[offName - 1] != '\\' && uBuf.Info.FileName[offName - 1] != '/')
offName--;
if (cwcNameOld == cwcNameNew)
<= pUniStr->MaximumLength)
{
pwszFixEnd -= cwcNameOld;
pwszFixEnd -= cwcNameNew;
}
/* else: ignore overflow. */
}
/* else: ignore failure. */
}
/* Advance */
}
}
static NTSTATUS supR3HardenedScreenImage(HANDLE hFile, bool fImage, PULONG pfAccess, PULONG pfProtect,
bool *pfQuietFailure)
{
*pfCallRealApi = false;
if (pfQuietFailure)
*pfQuietFailure = false;
/*
* Query the name of the file, making sure to zero terminator the
* string. (2nd half of buffer is used for error info, see below.)
*/
union
{
} uBuf;
NTSTATUS rcNt = NtQueryObject(hFile, ObjectNameInformation, &uBuf, sizeof(uBuf) - sizeof(WCHAR) - 128, &cbNameBuf);
if (!NT_SUCCESS(rcNt))
{
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedScreenImage/%s: NtQueryObject -> %#x (fImage=%d fProtect=%#x fAccess=%#x)\n",
return rcNt;
}
{
}
/*
* Check the cache.
*/
if (pCacheHit)
{
/* If we haven't done the WinVerifyTrust thing, do it if we can. */
if ( !pCacheHit->fWinVerifyTrust
{
if (!fAvoidWinVerifyTrust)
{
SUP_DPRINTF(("supR3HardenedScreenImage/%s: cache hit (%Rrc) on %ls [redoing WinVerifyTrust]\n",
bool fWinVerifyTrust = false;
int rc = supHardenedWinVerifyImageTrust(pCacheHit->hFile, pCacheHit->wszPath, pCacheHit->fFlags, pCacheHit->rc,
{
SUP_DPRINTF(("supR3HardenedScreenImage/%s: %d (was %d) fWinVerifyTrust=%d for '%ls'\n",
pCacheHit->fWinVerifyTrust = true;
}
else
SUP_DPRINTF(("supR3HardenedScreenImage/%s: WinVerifyTrust not available, rescheduling %ls\n",
}
else
SUP_DPRINTF(("supR3HardenedScreenImage/%s: cache hit (%Rrc) on %ls [avoiding WinVerifyTrust]\n",
}
SUP_DPRINTF(("supR3HardenedScreenImage/%s: cache hit (%Rrc) on %ls%s\n",
pszCaller, pCacheHit->rc, pCacheHit->wszPath, pCacheHit->fWinVerifyTrust ? "" : " [lacks WinVerifyTrust]"));
/* Return the cached value. */
{
*pfCallRealApi = true;
return STATUS_SUCCESS;
}
if ( cErrorHits < 8
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedScreenImage/%s: cached rc=%Rrc fImage=%d fProtect=%#x fAccess=%#x cErrorHits=%u %ls\n",
else if (pfQuietFailure)
*pfQuietFailure = true;
return STATUS_TRUST_FAILURE;
}
/*
* On XP the loader might hand us handles with just FILE_EXECUTE and
* SYNCHRONIZE, the means reading will fail later on. Also, we need
* READ_CONTROL access to check the file ownership later on, and non
* of the OS versions seems be giving us that. So, in effect we
* more or less always reopen the file here.
*/
&hMyFile,
0 /* Handle attributes*/, 0 /* Options */);
if (!NT_SUCCESS(rcNt))
{
if (rcNt == STATUS_ACCESS_DENIED)
{
InitializeObjectAttributes(&ObjAttr, &uBuf.UniStr, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
if (!NT_SUCCESS(rcNt))
{
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedScreenImage/%s: Failed to duplicate and open the file: rcNt=%#x hFile=%p %ls\n",
return rcNt;
}
/* Check that we've got the same file. */
if ( fMyValid
{
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedScreenImage/%s: Re-opened has different ID that input: %#llx vx %#llx (%ls)\n",
return STATUS_TRUST_FAILURE;
}
}
else
{
#ifdef DEBUG
supR3HardenedError(VINF_SUCCESS, false,
#endif
}
}
/*
* Special Kludge for Windows XP and W2K3 and their stupid attempts
* at mapping a hidden XML file called c:\Windows\WindowsShell.Manifest
* with executable access. The image bit isn't set, fortunately.
*/
if ( !fImage
{
PRTUTF16 pwszName = &uBuf.UniStr.Buffer[(g_System32NtPath.UniStr.Length - sizeof(L"System32") + sizeof(WCHAR)) / sizeof(WCHAR)];
{
/*
* Drop all executable access to the mapping and let it continue.
*/
SUP_DPRINTF(("supR3HardenedScreenImage/%s: Applying the drop-exec-kludge for '%ls'\n", pszCaller, uBuf.UniStr.Buffer));
if (*pfAccess & SECTION_MAP_EXECUTE)
if (*pfProtect & PAGE_EXECUTE)
*pfCallRealApi = true;
return STATUS_SUCCESS;
}
}
#ifndef VBOX_PERMIT_EVEN_MORE
/*
* Check the path. We don't allow DLLs to be loaded from just anywhere:
* 1. System32 - normal code or cat signing, owner TrustedInstaller.
* 2. WinSxS - normal code or cat signing, owner TrustedInstaller.
* 3. VirtualBox - kernel code signing and integrity checks.
* 4. AppPatchDir - normal code or cat signing, owner TrustedInstaller.
* 5. Program Files - normal code or cat signing, owner TrustedInstaller.
* 6. Common Files - normal code or cat signing, owner TrustedInstaller.
* 7. x86 variations of 4 & 5 - ditto.
*/
if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_System32NtPath.UniStr, true /*fCheckSlash*/))
else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_WinSxSNtPath.UniStr, true /*fCheckSlash*/))
g_offSupLibHardenedExeNtName, false /*fCheckSlash*/))
# ifdef VBOX_PERMIT_MORE
else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_ProgramFilesNtPath.UniStr, true /*fCheckSlash*/))
else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_CommonFilesNtPath.UniStr, true /*fCheckSlash*/))
# ifdef RT_ARCH_AMD64
else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_ProgramFilesX86NtPath.UniStr, true /*fCheckSlash*/))
else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_CommonFilesX86NtPath.UniStr, true /*fCheckSlash*/))
# endif
# endif
/* Hack to allow profiling our code with Visual Studio. */
&& memcmp(uBuf.UniStr.Buffer + (uBuf.UniStr.Length - sizeof(L"\\SamplingRuntime.dll") + sizeof(WCHAR)) / sizeof(WCHAR),
{
*pfCallRealApi = true;
return STATUS_SUCCESS;
}
# endif
else
{
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedScreenImage/%s: Not a trusted location: '%ls' (fImage=%d fProtect=%#x fAccess=%#x)\n",
return STATUS_TRUST_FAILURE;
}
#else /* VBOX_PERMIT_EVEN_MORE */
/*
* Require trusted installer + some kind of signature on everything, except
* for the VBox bits where we require kernel code signing and special
* integrity checks.
*/
g_offSupLibHardenedExeNtName, false /*fCheckSlash*/))
else
#endif /* VBOX_PERMIT_EVEN_MORE */
/*
* Do the verification. For better error message we borrow what's
* left of the path buffer for an RTERRINFO buffer.
*/
int rc;
bool fWinVerifyTrust = false;
rc = supHardenedWinVerifyImageByHandle(hMyFile, uBuf.UniStr.Buffer, fFlags, fAvoidWinVerifyTrust, &fWinVerifyTrust, &ErrInfo);
if (RT_FAILURE(rc))
{
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedScreenImage/%s: rc=%Rrc fImage=%d fProtect=%#x fAccess=%#x %ls: %s\n",
return STATUS_TRUST_FAILURE;
}
/*
* Insert into the cache.
*/
*pfCallRealApi = true;
return STATUS_SUCCESS;
}
/**
* Preloads a file into the verify cache if possible.
*
* This is used to avoid known cyclic LoadLibrary issues with WinVerifyTrust.
*
* @param pwszName The name of the DLL to verify.
*/
{
InitializeObjectAttributes(&ObjAttr, &UniStr, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
if (!NT_SUCCESS(rcNt))
{
return;
}
bool fCallRealApi;
//SUP_DPRINTF(("supR3HardenedWinVerifyCachePreload: scanning %ls\n", pwszName));
supR3HardenedScreenImage(hFile, false, &fAccess, &fProtect, &fCallRealApi, "preload", false /*fAvoidWinVerifyTrust*/,
NULL /*pfQuietFailure*/);
//SUP_DPRINTF(("supR3HardenedWinVerifyCachePreload: done %ls\n", pwszName));
}
/**
* Hook that monitors NtCreateSection calls.
*
* @returns NT status code.
* @param phSection Where to return the section handle.
* @param fAccess The desired access.
* @param pObjAttribs The object attributes (optional).
* @param pcbSection The section size (optional).
* @param fProtect The max section protection.
* @param fAttribs The section attributes.
* @param hFile The file to create a section from (optional).
*/
supR3HardenedMonitor_NtCreateSection(PHANDLE phSection, ACCESS_MASK fAccess, POBJECT_ATTRIBUTES pObjAttribs,
{
&& hFile != INVALID_HANDLE_VALUE)
{
bool const fExecProt = RT_BOOL(fProtect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_WRITECOPY
{
bool fCallRealApi;
//SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: 1\n"));
//SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: 2 rcNt=%#x fCallRealApi=%#x\n", rcNt, fCallRealApi));
if (!NT_SUCCESS(rcNt))
return rcNt;
if (!fCallRealApi)
return STATUS_TRUST_FAILURE;
}
}
/*
* Call checked out OK, call the original.
*/
return g_pfnNtCreateSectionReal(phSection, fAccess, pObjAttribs, pcbSection, fProtect, fAttribs, hFile);
}
/**
* Helper for supR3HardenedMonitor_LdrLoadDll.
*
* @returns NT status code.
* @param pwszPath The path destination buffer.
* @param cwcPath The size of the path buffer.
* @param pUniStrResult The result string.
* @param pOrgName The orignal name (for errors).
* @param pcwc Where to return the actual length.
*/
static NTSTATUS supR3HardenedCopyRedirectionResult(WCHAR *pwszPath, size_t cwcPath, PUNICODE_STRING pUniStrResult,
{
else
{
{
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedMonitor_LdrLoadDll: Name too long: %.*ls -> %.*ls (RtlDosApplyFileIoslationRedirection_Ustr)\n",
return STATUS_NAME_TOO_LONG;
}
}
return STATUS_SUCCESS;
}
/**
* Hooks that intercepts LdrLoadDll calls.
*
* Two purposes:
* -# Enforce our own search path restrictions.
* -# Prevalidate DLLs about to be loaded so we don't upset the loader data
* by doing it from within the NtCreateSection hook (WinVerifyTrust
* seems to be doing harm there on W7/32).
*
* @returns
* @param pwszSearchPath The search path to use.
* @param pfFlags Flags on input. DLL characteristics or something
* on return?
* @param pName The name of the module.
* @param phMod Where the handle of the loaded DLL is to be
* returned to the caller.
*/
supR3HardenedMonitor_LdrLoadDll(PWSTR pwszSearchPath, PULONG pfFlags, PUNICODE_STRING pName, PHANDLE phMod)
{
/*
* Make sure the DLL notification callback is registered. If we could, we
* would've done this during early process init, but due to lack of heap
* and uninitialized loader lock, it's not possible that early on.
*
* The callback protects our NtDll hooks from getting unhooked by
* "friendly" fire from the AV crowd.
*/
/*
* Process WinVerifyTrust todo before and after.
*/
/*
* Reject things we don't want to deal with.
*/
{
supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: name is NULL or have a zero length.\n");
SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x (pName=%p)\n", STATUS_INVALID_PARAMETER, pName));
return STATUS_INVALID_PARAMETER;
}
/*SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: pName=%.*ls *pfFlags=%#x pwszSearchPath=%p:%ls\n",
(unsigned)pName->Length / sizeof(WCHAR), pName->Buffer, pfFlags ? *pfFlags : UINT32_MAX, pwszSearchPath,
!((uintptr_t)pwszSearchPath & 1) && (uintptr_t)pwszSearchPath >= 0x2000U ? pwszSearchPath : L"<flags>"));*/
/*
* Reject long paths that's close to the 260 limit without looking.
*/
{
supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: too long name: %#x bytes\n", pName->Length);
return STATUS_NAME_TOO_LONG;
}
/*
* Absolute path?
*/
bool fSkipValidation = false;
)
{
NULL /*pNewFlags*/,
NULL /*pcbFilename*/,
NULL /*pcbNeeded*/);
if (NT_SUCCESS(rcNt))
{
rcNt = supR3HardenedCopyRedirectionResult(wszPath, RT_ELEMENTS(wszPath), pUniStrResult, pName, &cwc);
if (!NT_SUCCESS(rcNt))
{
return rcNt;
}
SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: '%.*ls' -> '%.*ls' [redir]\n",
pName = &ResolvedName;
}
else
{
}
}
/*
* Not an absolute path. Check if it's one of those special API set DLLs
* or something we're known to use but should be taken from WinSxS.
*/
L"api-ms-win-", 11, false /*fCheckSlash*/))
{
fSkipValidation = true;
}
/*
* Not an absolute path or special API set. There are two alternatives
* now, either there is no path at all or there is a relative path. We
* will resolve it to an absolute path in either case, failing the call
* if we can't.
*/
else
{
switch (pawcName[i])
{
case '\\':
case '/':
offLastSlash = i;
break;
case '.':
offLastDot = i;
break;
}
cwcName--;
/*
* Reject relative paths for now as they might be breakout attempts.
*/
if (offLastSlash != UINT32_MAX)
{
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedMonitor_LdrLoadDll: relative name not permitted: %.*ls\n",
return STATUS_OBJECT_NAME_INVALID;
}
/*
* Perform dll redirection to WinSxS such. We using an undocumented
* API here, which as always is a bit risky... ASSUMES that the API
* returns a full DOS path.
*/
NULL /*pNewFlags*/,
NULL /*pcbFilename*/,
NULL /*pcbNeeded*/);
if (NT_SUCCESS(rcNt))
{
rcNt = supR3HardenedCopyRedirectionResult(wszPath, RT_ELEMENTS(wszPath), pUniStrResult, pName, &cwc);
if (!NT_SUCCESS(rcNt))
{
return rcNt;
}
}
else
{
/*
* Search for the DLL. Only System32 is allowed as the target of
* a search on the API level, all VBox calls will have full paths.
*/
{
supR3HardenedError(VINF_SUCCESS, false,
return STATUS_NAME_TOO_LONG;
}
if (!fNeedDllSuffix)
else
{
cwc += 4;
}
}
SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: '%.*ls' -> '%.*ls' [rcNt=%#x]\n",
pName = &ResolvedName;
}
if (!fSkipValidation)
{
/*
* Try open the file. If this fails, never mind, just pass it on to
* the real API as we've replaced any searchable name with a full name
* and the real API can come up with a fitting status code for it.
*/
if (RT_FAILURE(rc))
{
supR3HardenedError(rc, false,
return STATUS_OBJECT_NAME_INVALID;
}
InitializeObjectAttributes(&ObjAttr, &NtPathUniStr, OBJ_CASE_INSENSITIVE, hRootDir, NULL /*pSecDesc*/);
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
if (NT_SUCCESS(rcNt))
{
bool fCallRealApi = false;
bool fQuietFailure = false;
if (!NT_SUCCESS(rcNt))
{
if (!fQuietFailure)
{
supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: rejecting '%ls': rcNt=%#x\n",
}
return rcNt;
}
}
else
{
SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: error opening '%ls': %u (NtPath=%.*ls)\n",
}
}
/*
* Screened successfully enough. Call the real thing.
*/
SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: pName=%.*ls *pfFlags=%#x pwszSearchPath=%p:%ls [calling]\n",
(unsigned)pName->Length / sizeof(WCHAR), pName->Buffer, pfFlags ? *pfFlags : UINT32_MAX, pwszSearchPath,
!((uintptr_t)pwszSearchPath & 1) && (uintptr_t)pwszSearchPath >= 0x2000U ? pwszSearchPath : L"<flags>"));
/*
* Log the result and process pending WinVerifyTrust work if we can.
*/
SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x hMod=%p '%ls'\n", rcNt, *phMod, wszPath));
else
return rcNt;
}
/**
* DLL load and unload notification callback.
*
* This is a safety against our LdrLoadDll hook being replaced by protection
* software. Though, we prefer the LdrLoadDll hook to this one as it allows us
* to call WinVerifyTrust more freely.
*
* @param ulReason The reason we're called, see
* LDR_DLL_NOTIFICATION_REASON_XXX.
* @param pData Reason specific data. (Format is currently the same for
* both load and unload.)
* @param pvUser User parameter (ignored).
*
* @remarks Vista and later.
* @remarks The loader lock is held when we're called, at least on Windows 7.
*/
static VOID CALLBACK supR3HardenedDllNotificationCallback(ULONG ulReason, PCLDR_DLL_NOTIFICATION_DATA pData, PVOID pvUser)
{
/*
* Screen the image on load. We will normally get a verification cache
* hit here because of the LdrLoadDll and NtCreateSection hooks, so it
* should be relatively cheap to recheck. In case our NtDll patches
* got re
*
* This ASSUMES that we get informed after the fact as indicated by the
* available documentation.
*/
{
SUP_DPRINTF(("supR3HardenedDllNotificationCallback: load %p LB %#010x %.*ls [fFlags=%#x]\n",
/* Convert the windows path to an NT path and open it. */
if (RT_FAILURE(rc))
{
supR3HardenedFatal("supR3HardenedDllNotificationCallback: RTNtPathFromWinUtf16Ex failed on '%.*ls': %Rrc\n",
return;
}
InitializeObjectAttributes(&ObjAttr, &NtPathUniStr, OBJ_CASE_INSENSITIVE, hRootDir, NULL /*pSecDesc*/);
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
if (!NT_SUCCESS(rcNt))
{
supR3HardenedFatal("supR3HardenedDllNotificationCallback: NtCreateFile failed on '%.*ls' / '%.*ls': %#x\n",
return;
}
/* Do the screening. */
bool fCallRealApi = false;
bool fQuietFailure = false;
if (!NT_SUCCESS(rcNt))
{
supR3HardenedFatal("supR3HardenedDllNotificationCallback: supR3HardenedScreenImage failed on '%.*ls' / '%.*ls': %#x\n",
return;
}
}
/*
* Log the unload call.
*/
else if (ulReason == LDR_DLL_NOTIFICATION_REASON_UNLOADED)
{
SUP_DPRINTF(("supR3HardenedDllNotificationCallback: Unload %p LB %#010x %.*ls [flags=%#x]\n",
}
/*
* Just log things we don't know and then return without caching anything.
*/
else
{
static uint32_t s_cLogEntries = 0;
if (s_cLogEntries++ < 32)
return;
}
/*
* Use this opportunity to make sure our NtDll patches are still in place,
* since they may be replaced by indecent protection software solutions.
*/
supR3HardenedWinReInstallHooks(false /*fFirstCall */);
}
/**
* Registers the DLL notification callback if it hasn't already been registered.
*/
static void supR3HardenedWinRegisterDllNotificationCallback(void)
{
/*
* The notification API was added in Vista, so it's an optional (weak) import.
*/
if ( LdrRegisterDllNotification != NULL
&& g_cDllNotificationRegistered <= 0
&& g_cDllNotificationRegistered > -32)
{
NTSTATUS rcNt = LdrRegisterDllNotification(0, supR3HardenedDllNotificationCallback, NULL, &g_pvDllNotificationCookie);
if (NT_SUCCESS(rcNt))
{
SUP_DPRINTF(("Registered Dll notification callback with NTDLL.\n"));
}
else
{
}
}
}
{
"Failed to install %s monitor: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n "
#ifdef RT_ARCH_X86
"(It is also possible you are running 32-bit VirtualBox under 64-bit windows.)\n"
#endif
,
}
/**
* IPRT thread that waits for the parent process to terminate and reacts by
* exiting the current process.
*
* @returns VINF_SUCCESS
* @param hSelf The current thread. Ignored.
* @param pvUser The handle of the parent process.
*/
{
/*
* Wait for the parent to terminate.
*/
for (;;)
{
if ( rcNt == STATUS_WAIT_0
|| rcNt == STATUS_ABANDONED_WAIT_0)
break;
if ( rcNt != STATUS_TIMEOUT
&& rcNt != STATUS_USER_APC
&& rcNt != STATUS_ALERTED)
}
/*
* Proxy the termination code of the child, if it exited already.
*/
NTSTATUS rcNt2 = NtQueryInformationProcess(hProcWait, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
if ( !NT_SUCCESS(rcNt2)
SUP_DPRINTF(("supR3HardenedWinParentWatcherThread: Quitting: ExitCode=%#x rcNt=%#x\n", BasicInfo.ExitStatus, rcNt));
return VINF_SUCCESS; /* won't be reached. */
}
/**
* Creates the parent watcher thread that will make sure this process exits when
* the parent does.
*
* This is a necessary evil to make VBoxNetDhcp and VBoxNetNat termination from
* Main work without too much new magic. It also makes Ctrl-C or similar work
* in on the hardened processes in the windows console.
*
* @param hVBoxRT The VBoxRT.dll handle. We use RTThreadCreate to
* spawn the thread to avoid duplicating thread
* creation and thread naming code from IPRT.
*/
{
/*
* Resolve runtime methods that we need.
*/
/*
* Find the parent process ID.
*/
NTSTATUS rcNt = NtQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
if (!NT_SUCCESS(rcNt))
supR3HardenedFatal("supR3HardenedWinCreateParentWatcherThread: NtQueryInformationProcess failed: %#x\n", rcNt);
/*
* Open the parent process for waiting and exitcode query.
*/
if (!NT_SUCCESS(rcNt))
supR3HardenedFatalMsg("supR3HardenedWinCreateParentWatcherThread", kSupInitOp_Misc, VERR_GENERAL_FAILURE,
/*
* Create the thread that should do the waiting.
*/
if (RT_FAILURE(rc))
}
/**
* Checks if the calling thread is the only one in the process.
*
* @returns true if we're positive we're alone, false if not.
*/
static bool supR3HardenedWinAmIAlone(void)
{
NTSTATUS rcNt = NtQueryInformationThread(NtCurrentThread(), ThreadAmILastThread, &fAmIAlone, sizeof(fAmIAlone), &cbIgn);
}
/**
* Simplify NtProtectVirtualMemory interface.
*
* Modifies protection for the current process. Caller must know the current
* protection as it's not returned.
*
* @returns NT status code.
* @param pvMem The memory to change protection for.
* @param cbMem The amount of memory to change.
* @param fNewProt The new protection.
*/
{
}
/**
* Installs or reinstalls the NTDLL patches.
*/
static void supR3HardenedWinReInstallHooks(bool fFirstCall)
{
struct
{
const char *pszName;
} const s_aPatches[] =
{
{ sizeof(g_abNtCreateSectionPatch), g_abNtCreateSectionPatch, &g_pbNtCreateSection, "NtCreateSection" },
};
{
{
/*
* Log the incident if it's not the initial call.
*/
{
s_cTimes++;
SUP_DPRINTF(("supR3HardenedWinReInstallHooks: Reinstalling %s (%p: %.*Rhxs).\n",
}
SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pbApi, s_aPatches[i].cbPatch, PAGE_EXECUTE_READWRITE));
/*
* If we're alone, just memcpy the patch in.
*/
if (fAmIAlone)
else
{
/*
* Not alone. Start by injecting a JMP $-2, then waste some
* CPU cycles to get the other threads a good chance of getting
* out of the code before we replace it.
*/
/* Copy in the tail bytes of the patch, then xchg the jmp $-2. */
}
SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pbApi, s_aPatches[i].cbPatch, PAGE_EXECUTE_READ));
}
}
}
/**
* Install hooks for intercepting calls dealing with mapping shared libraries
* into the process.
*
* This allows us to prevent undesirable shared libraries from being loaded.
*
* @remarks We assume we're alone in this process, so no seralizing trickery is
* necessary when installing the patch.
*
* @remarks We would normally just copy the prologue sequence somewhere and add
* a jump back at the end of it. But because we wish to avoid
* allocating executable memory, we need to have preprepared assembly
* "copies". This makes the non-system call patching a little tedious
* and inflexible.
*/
static void supR3HardenedWinInstallHooks(void)
{
/*
* Disable hard error popups so we can quietly refuse images to be loaded.
*/
rcNt = NtQueryInformationProcess(NtCurrentProcess(), ProcessDefaultHardErrorMode, &fHardErr, sizeof(fHardErr), NULL);
if (!NT_SUCCESS(rcNt))
"NtQueryInformationProcess/ProcessDefaultHardErrorMode failed: %#x\n", rcNt);
{
rcNt = NtSetInformationProcess(NtCurrentProcess(), ProcessDefaultHardErrorMode, &fHardErr, sizeof(fHardErr));
if (!NT_SUCCESS(rcNt))
"NtSetInformationProcess/ProcessDefaultHardErrorMode failed: %#x\n", rcNt);
}
/*
* Locate the routines first so we can allocate memory that's near enough.
*/
//SUPR3HARDENED_ASSERT(pfnNtCreateSection == (FARPROC)NtCreateSection);
//SUPR3HARDENED_ASSERT(pfnLdrLoadDll == (FARPROC)LdrLoadDll);
/*
* Exec page setup & management.
*/
uint32_t offExecPage = 0;
/*
* Hook #1 - NtCreateSection.
* Purpose: Validate everything that can be mapped into the process before
* it's mapped and we still have a file handle to work with.
*/
#ifdef RT_ARCH_AMD64
/*
* Patch 64-bit hosts.
*/
0:000> u ntdll!NtCreateSection
ntdll!NtCreateSection:
00000000`779f1750 4c8bd1 mov r10,rcx
00000000`779f1753 b847000000 mov eax,47h
00000000`779f1758 0f05 syscall
00000000`779f175a c3 ret
00000000`779f175b 0f1f440000 nop dword ptr [rax+rax]
The variant is the value loaded into eax: W2K3=??, Vista=47h?, W7=47h, W80=48h, W81=49h */
/* Assemble the patch. */
#else
/*
* Patch 32-bit hosts.
*/
/* Pattern #1: XP thru Windows 7
kd> u ntdll!NtCreateSection
ntdll!NtCreateSection:
7c90d160 b832000000 mov eax,32h
7c90d165 ba0003fe7f mov edx,offset SharedUserData!SystemCallStub (7ffe0300)
7c90d16a ff12 call dword ptr [edx]
7c90d16c c21c00 ret 1Ch
7c90d16f 90 nop
The variable bit is the value loaded into eax: XP=32h, W2K3=34h, Vista=4bh, W7=54h
Pattern #2: Windows 8.1
0:000:x86> u ntdll_6a0f0000!NtCreateSection
ntdll_6a0f0000!NtCreateSection:
6a15eabc b854010000 mov eax,154h
6a15eac1 e803000000 call ntdll_6a0f0000!NtCreateSection+0xd (6a15eac9)
6a15eac6 c21c00 ret 1Ch
6a15eac9 8bd4 mov edx,esp
6a15eacb 0f34 sysenter
6a15eacd c3 ret
The variable bit is the value loaded into eax: W81=154h */
/* Assemble the patch. */
#endif
/*
* Hook #2 - LdrLoadDll
* Purpose: (a) Enforce LdrLoadDll search path constraints, and (b) pre-validate
* DLLs so we can avoid calling WinVerifyTrust from the first hook,
* and thus avoiding messing up the loader data on some installations.
*
* This differs from the above function in that is no a system call and
* we're at the mercy of the compiler.
*/
uint32_t offJmpBack = 0;
#ifdef RT_ARCH_AMD64
/*
* Patch 64-bit hosts.
*/
/* Just use the disassembler to skip 12 bytes or more. */
while (offJmpBack < 12)
{
cbInstr = 1;
if ( RT_FAILURE(rc)
offJmpBack += cbInstr;
}
/* Assemble the code for resuming the call.*/
*(uint32_t *)&g_abSupHardReadWriteExecPage[offExecPage] = RT_ALIGN_32(offExecPage + 4, 8) - (offExecPage + 4);
/* Assemble the LdrLoadDll patch. */
#else
/*
* Patch 32-bit hosts.
*/
/* Just use the disassembler to skip 5 bytes or more. */
while (offJmpBack < 5)
{
cbInstr = 1;
if ( RT_FAILURE(rc)
offJmpBack += cbInstr;
}
/* Assemble the code for resuming the call.*/
/* Assemble the LdrLoadDll patch. */
g_abLdrLoadDllPatch[0] = 0xe9;
*(uint32_t *)&g_abLdrLoadDllPatch[1] = (uintptr_t)supR3HardenedMonitor_LdrLoadDll - (uintptr_t)&pbLdrLoadDll[1+4];
#endif
/*
* Seal the rwx page.
*/
SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(g_abSupHardReadWriteExecPage, PAGE_SIZE, PAGE_EXECUTE_READ));
/*
* Install the patches.
*/
supR3HardenedWinReInstallHooks(true /*fFirstCall*/);
}
/*
*
* T h r e a d c r e a t i o n c o n t r o l
* T h r e a d c r e a t i o n c o n t r o l
* T h r e a d c r e a t i o n c o n t r o l
*
*/
/**
* Common code used for child and parent to make new threads exit immediately.
*
* This patches the LdrInitializeThunk code to call NtTerminateThread with
* STATUS_SUCCESS instead of doing the NTDLL initialization.
*
* @returns VBox status code.
* @param hProcess The process to do this to.
* @param pvLdrInitThunk The address of the LdrInitializeThunk code to
* override.
* @param pvNtTerminateThread The address of the NtTerminateThread function in
* the NTDLL instance we're patching. (Must be +/-
* 2GB from the thunk code.)
* @param pabBackup Where to back up the original instruction bytes
* at pvLdrInitThunk.
* @param cbBackup The size of the backup area. Must be 16 bytes.
* @param pErrInfo Where to return extended error information.
* Optional.
*/
static int supR3HardNtDisableThreadCreationEx(HANDLE hProcess, void *pvLdrInitThunk, void *pvNtTerminateThread,
{
SUP_DPRINTF(("supR3HardNtDisableThreadCreation: pvLdrInitThunk=%p pvNtTerminateThread=%p\n", pvLdrInitThunk, pvNtTerminateThread));
/*
* Back up the thunk code.
*/
if (!NT_SUCCESS(rcNt))
"supR3HardNtDisableThreadCreation: NtReadVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
/*
* Cook up replacement code that calls NtTerminateThread.
*/
#ifdef RT_ARCH_AMD64
*(int32_t *)&abReplacement[5] = (int32_t)((uintptr_t)pvNtTerminateThread - ((uintptr_t)pvLdrInitThunk + 9));
#elif defined(RT_ARCH_X86)
*(int32_t *)&abReplacement[5] = (int32_t)((uintptr_t)pvNtTerminateThread - ((uintptr_t)pvLdrInitThunk + 9));
#else
# error "Unsupported arch."
#endif
/*
* Install the replacment code.
*/
if (!NT_SUCCESS(rcNt))
"supR3HardNtDisableThreadCreationEx: NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
rcNt = NtWriteVirtualMemory(hProcess, pvLdrInitThunk, abReplacement, sizeof(abReplacement), &cbIgnored);
if (!NT_SUCCESS(rcNt))
"supR3HardNtDisableThreadCreationEx: NtWriteVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
if (!NT_SUCCESS(rcNt))
"supR3HardNtDisableThreadCreationEx: NtProtectVirtualMemory/LdrInitializeThunk/2 failed: %#x", rcNt);
return VINF_SUCCESS;
}
/**
* Undo the effects of supR3HardNtDisableThreadCreationEx.
*
* @returns VBox status code.
* @param hProcess The process to do this to.
* @param pvLdrInitThunk The address of the LdrInitializeThunk code to
* override.
* @param pabBackup Where to back up the original instruction bytes
* at pvLdrInitThunk.
* @param cbBackup The size of the backup area. Must be 16 bytes.
* @param pErrInfo Where to return extended error information.
* Optional.
*/
static int supR3HardNtEnableThreadCreationEx(HANDLE hProcess, void *pvLdrInitThunk, uint8_t const *pabBackup, size_t cbBackup,
{
SUP_DPRINTF(("supR3HardNtEnableThreadCreation:\n"));
NTSTATUS rcNt = NtProtectVirtualMemory(hProcess, &pvProt, &cbProt, PAGE_EXECUTE_READWRITE, &fOldProt);
if (!NT_SUCCESS(rcNt))
"supR3HardNtDisableThreadCreationEx: NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
if (!NT_SUCCESS(rcNt))
"supR3HardNtEnableThreadCreation: NtWriteVirtualMemory/LdrInitializeThunk[restore] failed: %#x",
rcNt);
if (!NT_SUCCESS(rcNt))
"supR3HardNtEnableThreadCreation: NtProtectVirtualMemory/LdrInitializeThunk[restore] failed: %#x",
rcNt);
return VINF_SUCCESS;
}
/**
* Disable thread creation for the current process.
*
* @remarks Doesn't really disables it, just makes the threads exit immediately
* without executing any real code.
*/
static void supR3HardenedWinDisableThreadCreation(void)
{
/* Cannot use the imported NtTerminateThread as it's pointing to our own
syscall assembly code. */
if (s_pfnNtTerminateThread == NULL)
(void *)(uintptr_t)&LdrInitializeThunk,
(void *)(uintptr_t)s_pfnNtTerminateThread,
NULL /* pErrInfo*/);
}
/**
* Undoes the effects of supR3HardenedWinDisableThreadCreation.
*/
DECLHIDDEN(void) supR3HardenedWinEnableThreadCreation(void)
{
{
(void *)(uintptr_t)&LdrInitializeThunk,
if (RT_FAILURE(rc))
g_fSupInitThunkSelfPatched = false;
}
}
/*
*
* R e s p a w n
* R e s p a w n
* R e s p a w n
*
*/
/**
* Gets the SID of the user associated with the process.
*
* @returns @c true if we've got a login SID, @c false if not.
* @param pSidUser Where to return the user SID.
* @param cbSidUser The size of the user SID buffer.
* @param pSidLogin Where to return the login SID.
* @param cbSidLogin The size of the login SID buffer.
*/
static bool supR3HardNtChildGetUserAndLogSids(PSID pSidUser, ULONG cbSidUser, PSID pSidLogin, ULONG cbSidLogin)
{
union
{
} uBuf;
SUPR3HARDENED_ASSERT_NT_SUCCESS(NtQueryInformationToken(hToken, TokenUser, &uBuf, sizeof(uBuf), &cbRet));
bool fLoginSid = false;
if (NT_SUCCESS(rcNt))
{
{
fLoginSid = true;
break;
}
}
return fLoginSid;
}
/**
* Build security attributes for the process or the primary thread (@a fProcess)
*
* Process DACLs can be bypassed using the SeDebugPrivilege (generally available
* modifying the DACL. However, it restricts
*
* @param pSecAttrs Where to return the security attributes.
* @param pCleanup Cleanup record.
* @param fProcess Set if it's for the process, clear if it's for
* the primary thread.
*/
static void supR3HardNtChildInitSecAttrs(PSECURITY_ATTRIBUTES pSecAttrs, PMYSECURITYCLEANUP pCleanup, bool fProcess)
{
/*
* Safe return values.
*/
/** @todo This isn't at all complete, just sketches... */
/*
* Create an ACL detailing the access of the above groups.
*/
SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCreateAcl(&pCleanup->Acl.AclHdr, sizeof(pCleanup->Acl), ACL_REVISION));
if (fProcess)
{
{
}
}
else
{
fDeny |= THREAD_SUSPEND_RESUME | THREAD_SET_CONTEXT | THREAD_SET_INFORMATION | THREAD_SET_THREAD_TOKEN
{
}
}
/* Deny everyone access to bad bits. */
#if 1
#endif
#if 0
/* Grant some access to the owner - doesn't work. */
#endif
#if 1
# if 1
/* Grant minimal access to the user. */
# endif
# if 1
/* Grant very limited access to the login sid. */
if (fHasLoginSid)
{
}
# endif
#endif
/*
* Create a security descriptor with the above ACL.
*/
SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCreateSecurityDescriptor(pSecDesc, SECURITY_DESCRIPTOR_REVISION));
SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlSetDaclSecurityDescriptor(pSecDesc, TRUE /*fDaclPresent*/, &pCleanup->Acl.AclHdr,
FALSE /*fDaclDefaulted*/));
}
/**
* Predicate function which tests whether @a ch is a argument separator
* character.
*
* @param ch The character to examine.
*/
{
return ch == ' '
|| ch == '\t'
|| ch == '\n'
|| ch == '\r';
}
/**
* Construct the new command line.
*
* suplibHardenedWindowsMain), we skip the argument by argument UTF-8 -> UTF-16
* conversion and quoting by going to the original source.
*
* The executable name, though, is replaced in case it's not a fullly
* qualified path.
*
* The re-spawn indicator is added immediately after the executable name
* so that we don't get tripped up missing close quote chars in the last
* argument.
*
* @returns Pointer to a command line string (heap).
* @param pUniStr Unicode string structure to initialize to the
* command line. Optional.
* @param iWhich Which respawn we're to check for, 1 being the first
* one, and 2 the second and final.
*/
{
/*
* Get the command line and skip the executable name.
*/
/* Skip leading space (shouldn't be any, but whatever). */
/* Walk to the end of it. */
int fQuoted = false;
do
{
if (*pawcArgs == '"')
{
}
else
{
unsigned cSlashes = 0;
do
{
cSlashes++;
cwcArgs--;
pawcArgs++;
}
}
/* Skip trailing spaces. */
/*
* Allocate a new buffer.
*/
size_t cwcCmdLine = (sizeof(SUPR3_RESPAWN_1_ARG0) - 1) / sizeof(SUPR3_RESPAWN_1_ARG0[0]) /* Respawn exe name. */
"Command line is too long (%u chars)!", cwcCmdLine);
/*
* Construct the new command line.
*/
for (const char *pszSrc = iWhich == 1 ? SUPR3_RESPAWN_1_ARG0 : SUPR3_RESPAWN_2_ARG0; *pszSrc; pszSrc++)
if (cwcArgs)
{
*pwszDst++ = ' ';
}
*pwszDst = '\0';
if (pString)
{
}
return pwszCmdLine;
}
/**
* Terminates the child process.
*
* @param hProcess The process handle.
* @param pszWhere Who's having child rasing troubles.
* @param rc The status code to report.
* @param pszFormat The message format string.
* @param ... Message format arguments.
*/
static void supR3HardenedWinKillChild(HANDLE hProcess, const char *pszWhere, int rc, const char *pszFormat, ...)
{
/*
* Terminate the process ASAP and display error.
*/
/*
* Wait for the process to really go away.
*/
NTSTATUS rcNtExit = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
if (!fExitOk)
{
do
{
rcNtExit = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
} while ( !fExitOk
&& ( rcNtWait == STATUS_TIMEOUT
|| rcNtWait == STATUS_USER_APC
|| rcNtWait == STATUS_ALERTED)
if (fExitOk)
"NtDuplicateObject failed and we failed to kill child: rc=%u (%#x) rcNtWait=%#x hProcess=%p\n",
}
/*
* Final error message.
*/
}
/**
* Checks the child process when hEvtParent is signalled.
*
* This will read the request data from the child and check it against expected
* request. If an error is signalled, we'll raise it and make sure the child
* terminates before terminating the calling process.
*
* @param pThis The child process data structure.
* @param enmExpectedRequest The expected child request.
* @param pszWhat What we're waiting for.
*/
static void supR3HardNtChildProcessRequest(PSUPR3HARDNTCHILD pThis, SUPR3WINCHILDREQ enmExpectedRequest, const char *pszWhat)
{
/*
* Read the process parameters from the child.
*/
if (!NT_SUCCESS(rcNt))
/*
* Is it the expected request?
*/
return;
/*
* No, not the expected request. If it's an error request, tell the child
* to terminate itself, otherwise we'll have to terminate it.
*/
SUP_DPRINTF(("supR3HardenedWinCheckChild: enmRequest=%d rc=%d enmWhat=%d %s: %s\n",
"Unexpected child request #%d. Was expecting #%d (%s).\n",
if (!NT_SUCCESS(rcNt))
supR3HardenedWinKillChild(pThis, "supR3HardNtChildProcessRequest", rcNt, "NtSetEvent failed: %#x\n", rcNt);
/* Wait for it to terminate. */
if (rcNt != STATUS_WAIT_0)
{
SUP_DPRINTF(("supR3HardNtChildProcessRequest: Child is taking too long to quit (rcWait=%#x), killing it...\n", rcNt));
}
/*
* Report the error in the same way as it occured in the guest.
*/
else
}
/**
* Waits for the child to make a certain request or terminate.
*
* The stub process will also wait on it's parent to terminate.
* This call will only return if the child made the expected request.
*
* @param pThis The child process data structure.
* @param enmExpectedRequest The child request to wait for.
* @param cMsTimeout The number of milliseconds to wait (at least).
* @param pszWhat What we're waiting for.
*/
static void supR3HardNtChildWaitFor(PSUPR3HARDNTCHILD pThis, SUPR3WINCHILDREQ enmExpectedRequest, RTMSINTERVAL cMsTimeout,
const char *pszWhat)
{
/*
* The wait loop.
* Will return when the expected request arrives.
* Will break out when one of the processes terminates.
*/
uint64_t cMsElapsed = 0;
for (;;)
{
/*
* Assemble handles to wait for.
*/
if (pThis->hEvtParent)
/*
* Do the waiting according to the callers wishes.
*/
|| cMsTimeout == RT_INDEFINITE_WAIT)
rcNtWait = NtWaitForMultipleObjects(cHandles, &ahHandles[0], WaitAnyObject, TRUE /*Alertable*/, NULL /*Timeout*/);
else
{
rcNtWait = NtWaitForMultipleObjects(cHandles, &ahHandles[0], WaitAnyObject, TRUE /*Alertable*/, &Timeout);
}
/*
* Process child request.
*/
{
SUP_DPRINTF(("supR3HardNtChildWaitFor: Found expected request %d (%s) after %llu ms.\n",
return; /* Expected request received. */
}
/*
* Process termination?
*/
break;
/*
* Check sanity.
*/
if ( rcNtWait != STATUS_TIMEOUT
&& rcNtWait != STATUS_USER_APC
&& rcNtWait != STATUS_ALERTED)
"NtWaitForMultipleObjects returned %#x waiting for #%d (%s)\n",
/*
* Calc elapsed time for the next timeout calculation, checking to see
* if we've timed out already.
*/
if ( cMsElapsed > cMsTimeout
&& cMsTimeout != RT_INDEFINITE_WAIT
{
else
{
/* We timed out. */
"Timed out after %llu ms waiting for child request #%d (%s).\n",
}
}
}
/*
* Proxy the termination code of the child, if it exited already.
*/
NTSTATUS rcNt1 = NtQueryInformationProcess(pThis->hProcess, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
if ( !NT_SUCCESS(rcNt1)
{
}
SUP_DPRINTF(("supR3HardNtChildWaitFor[%d]: Quitting: ExitCode=%#x (rcNtWait=%#x, rcNt1=%#x, rcNt2=%#x, rcNt3=%#x, %llu ms, %s);\n",
}
/**
* Closes full access child thread and process handles, making a harmless
* duplicate of the process handle first.
*
* The hProcess member of the child process data structure will be change to the
* harmless handle, while the hThread will be set to NULL.
*
* @param pThis The child process data structure.
*/
{
/*
* The thread handle.
*/
if (!NT_SUCCESS(rcNt))
supR3HardenedWinKillChild(pThis, "supR3HardenedWinReSpawn", rcNt, "NtClose(hThread) failed: %#x", rcNt);
/*
* Duplicate the process handle into a harmless one.
*/
else
fRights, 0 /*HandleAttributes*/, 0);
if (rcNt == STATUS_ACCESS_DENIED)
{
"supR3HardenedWinDoReSpawn: NtDuplicateObject(,,,,%#x,,) -> %#x, retrying with only %#x...\n",
SYNCHRONIZE, 0 /*HandleAttributes*/, 0);
}
if (!NT_SUCCESS(rcNt))
"NtDuplicateObject failed on child process handle: %#x\n", rcNt);
/*
* Close the process handle and replace it with the harmless one.
*/
if (!NT_SUCCESS(rcNt))
"NtClose failed on child process handle: %#x\n", rcNt);
}
/**
* This restores the child PEB and tweaks a couple of fields before we do the
* child purification and let the process run normally.
*
* @param pThis The child process data structure.
*/
{
/*
* Make a copy of the pre-execution PEB.
*/
#if 0
/*
* There should not be any activation context, so if there is, we scratch the memory associated with it.
*/
int rc = 0;
if (RT_SUCCESS(rc) && Peb.ActivationContextData && !((uintptr_t)Peb.ActivationContextData & PAGE_OFFSET_MASK))
rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.ActivationContextData, PAGE_SIZE, "ActivationContextData", pErrInfo);
if (RT_SUCCESS(rc) && Peb.ProcessAssemblyStorageMap && !((uintptr_t)Peb.ProcessAssemblyStorageMap & PAGE_OFFSET_MASK))
rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.ProcessAssemblyStorageMap, PAGE_SIZE, "ProcessAssemblyStorageMap", pErrInfo);
if (RT_SUCCESS(rc) && Peb.SystemDefaultActivationContextData && !((uintptr_t)Peb.SystemDefaultActivationContextData & PAGE_OFFSET_MASK))
rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.ProcessAssemblyStorageMap, PAGE_SIZE, "SystemDefaultActivationContextData", pErrInfo);
if (RT_SUCCESS(rc) && Peb.SystemAssemblyStorageMap && !((uintptr_t)Peb.SystemAssemblyStorageMap & PAGE_OFFSET_MASK))
rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.SystemAssemblyStorageMap, PAGE_SIZE, "SystemAssemblyStorageMap", pErrInfo);
if (RT_FAILURE(rc))
return rc;
#endif
/*
* Clear compatibility and activation related fields.
*/
#if 0
/*Peb.Diff0.W6.IsProtectedProcess = 1;*/
#endif
/*
* Write back the PEB.
*/
NTSTATUS rcNt = NtWriteVirtualMemory(pThis->hProcess, pThis->BasicInfo.PebBaseAddress, &Peb, pThis->cbPeb, &cbActualMem);
if (!NT_SUCCESS(rcNt))
"NtWriteVirtualMemory/Peb failed: %#x", rcNt);
}
/**
* Purifies the child process after very early init has been performed.
*
* @param pThis The child process data structure.
*/
{
/*
* We loop until we no longer make any fixes. This is similar to what
* we do (or used to do, really) in the fAvastKludge case of
* supR3HardenedWinInit. We might be up against asynchronous changes,
* which we fudge by waiting a short while before earch purification. This
* is arguably a fragile technique, but it's currently the best we've got.
* Fortunately, most AVs seems to either favor immediate action on initial
* load events or (much better for us) later events like kernel32.
*/
uint32_t cTotalFixes = 0;
{
/*
* Delay.
*/
do
{
cSleeps++;
|| cSleeps < 8);
SUP_DPRINTF(("supR3HardNtChildPurify: Startup delay kludge #1/%u: %u ms, %u sleeps\n",
/*
* Purify.
*/
cFixes = 0;
int rc = supHardenedWinVerifyProcess(pThis->hProcess, pThis->hThread, SUPHARDNTVPKIND_CHILD_PURIFICATION,
if (RT_FAILURE(rc))
if (cFixes == 0)
{
SUP_DPRINTF(("supR3HardNtChildPurify: Done after %llu ms and %u fixes (loop #%u).\n",
return; /* We're probably good. */
}
cTotalFixes += cFixes;
if (!g_fSupAdversaries)
cMsFudge = 512;
/*
* Log the KiOpPrefetchPatchCount value if available, hoping it might
* sched some light on spider38's case.
*/
ULONG cPatchCount = 0;
if (NT_SUCCESS(rcNt))
SUP_DPRINTF(("supR3HardNtChildPurify: cFixes=%u g_fSupAdversaries=%#x cPatchCount=%#u\n",
else
SUP_DPRINTF(("supR3HardNtChildPurify: cFixes=%u g_fSupAdversaries=%#x\n", cFixes, g_fSupAdversaries));
}
/*
* We've given up fixing the child process. Probably fighting someone
*/
"Unable to purify child process! After 16 tries over %llu ms, we still %u fix(es) in the last pass.",
}
/**
* Sets up the early process init.
*
* @param pThis The child process data structure.
*/
{
/*
* Plant the process parameters. This ASSUMES the handle inheritance is
* performed when creating the child process.
*/
uintptr_t uChildAddr = uChildExeAddr + ((uintptr_t)&g_ProcParams - (uintptr_t)NtCurrentPeb()->ImageBaseAddress);
if (!NT_SUCCESS(rcNt))
/*
* Locate the LdrInitializeThunk address in the child as well as pristine
* code bits for it.
*/
if (RT_FAILURE(rc))
"supHardNtLdrCacheOpen failed on NTDLL: %Rrc\n", rc);
rc = supHardNtLdrCacheEntryGetBits(pLdrEntry, &pbChildNtDllBits, pThis->uNtDllAddr, NULL, NULL, NULL /*pErrInfo*/);
if (RT_FAILURE(rc))
"supHardNtLdrCacheEntryGetBits failed on NTDLL: %Rrc\n", rc);
"LdrInitializeThunk", &uLdrInitThunk);
if (RT_FAILURE(rc))
"Error locating LdrInitializeThunk in NTDLL: %Rrc", rc);
/*
* Calculate the address of our code in the child process.
*/
/*
* Compose the LdrInitializeThunk replacement bytes.
* Note! The amount of code we replace here must be less or equal to what
* the process verification code ignores.
*/
#ifdef RT_ARCH_AMD64
abNew[0] = 0xff;
#elif defined(RT_ARCH_X86)
abNew[0] = 0xe9;
#else
# error "Unsupported arch."
#endif
/*
* Install the LdrInitializeThunk replacement code in the child process.
*/
rcNt = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, PAGE_EXECUTE_READWRITE, &fOldProt);
if (!NT_SUCCESS(rcNt))
"NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
if (!NT_SUCCESS(rcNt))
"NtWriteVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
if (!NT_SUCCESS(rcNt))
"NtProtectVirtualMemory/LdrInitializeThunk[restore] failed: %#x", rcNt);
/* Caller starts child execution. */
SUP_DPRINTF(("supR3HardenedWinSetupChildInit: Start child.\n"));
}
/**
* This messes with the child PEB before we trigger the initial image events.
*
* @param pThis The child process data structure.
*/
{
/*
* Not sure if any of the cracker software uses the PEB at this point, but
* just in case they do make some of the PEB fields a little less useful.
*/
/* Make ImageBaseAddress useless. */
#ifdef RT_ARCH_AMD64
#endif
/*
* Write the PEB.
*/
NTSTATUS rcNt = NtWriteVirtualMemory(pThis->hProcess, pThis->BasicInfo.PebBaseAddress, &Peb, pThis->cbPeb, &cbActualMem);
if (!NT_SUCCESS(rcNt))
"NtWriteVirtualMemory/Peb failed: %#x", rcNt);
}
/**
* Check if the zero terminated NT unicode string is the path to the given
* system32 DLL.
*
* @returns true if it is, false if not.
* @param pUniStr The zero terminated NT unicode string path.
* @param pszName The name of the system32 DLL.
*/
{
{
{
{
if (RTUtf16ICmpAscii(&pUniStr->Buffer[g_System32NtPath.UniStr.Length / sizeof(WCHAR) + 1], pszName) == 0)
return true;
}
}
}
return false;
}
/**
* Worker for supR3HardNtChildGatherData that locates NTDLL in the child
* process.
*
* @param pThis The child process data structure.
*/
{
/*
* Find NTDLL in this process first and take that as a starting point.
*/
SUPR3HARDENED_ASSERT(pThis->uNtDllParentAddr != 0 && !(pThis->uNtDllParentAddr & PAGE_OFFSET_MASK));
/*
* Scan the virtual memory of the child.
*/
for (uint32_t i = 0; i < 1024; i++)
{
/* Query information. */
MEMORY_BASIC_INFORMATION MemInfo = { 0, 0, 0, 0, 0, 0, 0 };
(void const *)uPtrWhere,
&MemInfo,
sizeof(MemInfo),
&cbActual);
if (!NT_SUCCESS(rcNt))
break;
{
{
/* Get the image name. */
union
{
} uBuf;
&uBuf,
&cbActual);
if (NT_SUCCESS(rcNt))
{
{
SUP_DPRINTF(("supR3HardNtPuChFindNtdll: uNtDllParentAddr=%p uNtDllChildAddr=%p\n",
return;
}
}
}
}
/*
* Advance.
*/
break;
}
supR3HardenedWinKillChild(pThis, "supR3HardNtChildFindNtdll", VERR_MODULE_NOT_FOUND, "ntdll.dll not found in child process.");
}
/**
* Gather child data.
*
* @param This The child process data structure.
*/
{
/*
* Basic info.
*/
if (!NT_SUCCESS(rcNt))
"NtQueryInformationProcess/ProcessBasicInformation failed: %#x", rcNt);
/*
* If this is the middle (stub) process, we wish to wait for both child
* and parent. So open the parent process. Not fatal if we cannnot.
*/
{
rcNt = NtOpenProcess(&pThis->hParent, SYNCHRONIZE | PROCESS_QUERY_INFORMATION, &ObjAttr, &ClientId);
#ifdef DEBUG
#endif
if (!NT_SUCCESS(rcNt))
{
SUP_DPRINTF(("supR3HardNtChildGatherData: Failed to open parent process (%#p): %#x\n", ClientId.UniqueProcess, rcNt));
}
}
/*
* Process environment block.
*/
if (g_uNtVerCombined < SUP_NT_VER_W2K3)
else if (g_uNtVerCombined < SUP_NT_VER_VISTA)
else if (g_uNtVerCombined < SUP_NT_VER_W70)
else if (g_uNtVerCombined < SUP_NT_VER_W80)
else if (g_uNtVerCombined < SUP_NT_VER_W81)
else
SUP_DPRINTF(("supR3HardNtChildGatherData: PebBaseAddress=%p cbPeb=%#x\n",
rcNt = NtReadVirtualMemory(pThis->hProcess, pThis->BasicInfo.PebBaseAddress, &pThis->Peb, sizeof(pThis->Peb), &cbActualMem);
if (!NT_SUCCESS(rcNt))
"NtReadVirtualMemory/Peb failed: %#x", rcNt);
/*
* Locate NtDll.
*/
}
/**
* Does the actually respawning.
*
* @returns Never, will call exit or raise fatal error.
* @param iWhich Which respawn we're to check for, 1 being the
* first one, and 2 the second and final.
*/
static void supR3HardenedWinDoReSpawn(int iWhich)
{
/*
* Init the child process data structure, creating the child communication
* event sempahores.
*/
InitializeObjectAttributes(&ObjAttrs, NULL /*pName*/, OBJ_INHERIT, NULL /*hRootDir*/, NULL /*pSecDesc*/);
SUPR3HARDENED_ASSERT_NT_SUCCESS(NtCreateEvent(&This.hEvtChild, EVENT_ALL_ACCESS, &ObjAttrs, SynchronizationEvent, FALSE));
InitializeObjectAttributes(&ObjAttrs, NULL /*pName*/, OBJ_INHERIT, NULL /*hRootDir*/, NULL /*pSecDesc*/);
SUPR3HARDENED_ASSERT_NT_SUCCESS(NtCreateEvent(&This.hEvtParent, EVENT_ALL_ACCESS, &ObjAttrs, SynchronizationEvent, FALSE));
/*
* Set up security descriptors.
*/
#if 1
/*
* Configure the startup info and creation flags.
*/
if (1)
else
{
/** @todo experiment with protected process stuff later on. */
}
/*
* Construct the command line and launch the process.
*/
TRUE /*fInheritHandles*/,
NULL /*pwszzEnvironment*/,
NULL /*pwszCurDir*/,
"Error relaunching VirtualBox VM process: %u\n"
"Command line: '%ls'",
SUP_DPRINTF(("supR3HardenedWinDoReSpawn(%d): New child %x.%x [kernel32].\n",
#else
/*
* Construct the process parameters.
*/
W32ImageName.Buffer = g_wszSupLibHardenedExePath; /* Yes the windows name for the process parameters. */
NULL /* DllPath - inherit from this process */,
NULL /* CurrentDirectory - inherit from this process */,
&CmdLine,
NULL /* Environment - inherit from this process */,
NULL /* WindowsTitle - none */,
NULL /* DesktopTitle - none. */,
NULL /* ShellInfo - none. */,
NULL /* RuntimeInfo - none (byte array for MSVCRT file info) */)
);
/** @todo this doesn't work. :-( */
NULL, //&ProcessSecAttrs,
NULL, //&ThreadSecAttrs,
NtCurrentProcess() /* ParentProcess */,
FALSE /*fInheritHandles*/,
NULL /* DebugPort */,
NULL /* ExceptionPort */,
if (!NT_SUCCESS(rcNt))
"Error relaunching VirtualBox VM process: %#x\n"
"Command line: '%ls'",
SUP_DPRINTF(("supR3HardenedWinDoReSpawn(%d): New child %x.%x [ntdll].\n",
#endif
#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
/*
* Apply anti debugger notification trick to the thread. (Also done in
* supR3HardenedWinInit.) This may fail with STATUS_ACCESS_DENIED and
* maybe other errors.
*/
if (!NT_SUCCESS(rcNt))
SUP_DPRINTF(("supR3HardenedWinReSpawn: NtSetInformationThread/ThreadHideFromDebugger failed: %#x (harmless)\n", rcNt));
#endif
/*
* Perform very early child initialization.
*/
ULONG cSuspendCount = 0;
if (!NT_SUCCESS(rcNt))
supR3HardenedWinKillChild(&This, "supR3HardenedWinDoReSpawn", rcNt, "NtResumeThread failed: %#x", rcNt);
/*
* Santizie the pre-NTDLL child when it's ready.
*
* AV software and other things injecting themselves into the embryonic
* and budding process to intercept API calls and what not. Unfortunately
* this is also the behavior of viruses, malware and other unfriendly
* software, so we won't stand for it. AV software can scan our image
* as they are loaded via kernel hooks, that's sufficient. No need for
* patching half of NTDLL or messing with the import table of the
* process executable.
*/
supR3HardNtChildWaitFor(&This, kSupR3WinChildReq_PurifyChildAndCloseHandles, 2000 /*ms*/, "PurifyChildAndCloseHandles");
/*
* Close the unrestricted access handles. Since we need to wait on the
* child process, we'll reopen the process with limited access before doing
* away with the process handle returned by CreateProcess.
*/
/*
* Signal the child that we've closed the unrestricted handles and it can
* safely try open the driver.
*/
if (!NT_SUCCESS(rcNt))
"NtSetEvent failed on child process handle: %#x\n", rcNt);
/*
* Ditch the loader cache so we don't sit on too much memory while waiting.
*/
/*
* Enable thread creation at this point so Ctrl-C and Ctrl-Break can be processed.
*/
/*
* Wait for the child to get to suplibHardenedWindowsMain so we can close the handles.
*/
/*
* Wait for the process to terminate.
*/
SUPR3HARDENED_ASSERT(false); /* We're not supposed to get here! */
}
/**
* Logs the content of the given object directory.
*
* @returns true if it exists, false if not.
* @param pszDir The path of the directory to log (ASCII).
*/
static void supR3HardenedWinLogObjDir(const char *pszDir)
{
/*
* Open the driver object directory.
*/
if (RT_FAILURE(rc))
{
return;
}
InitializeObjectAttributes(&ObjAttr, &NtDirName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
if (!NT_SUCCESS(rcNt))
return;
/*
* Enumerate it, looking for the driver.
*/
ULONG uObjDirCtx = 0;
for (;;)
{
FALSE /*ReturnSingleEntry */,
FALSE /*RestartScan*/,
&cbActual);
{
SUP_DPRINTF(("supR3HardenedWinLogObjDir: NtQueryDirectoryObject => rcNt=%#x cbActual=%#x\n", rcNt, cbActual));
break;
}
{
SUP_DPRINTF((" %.*ls %.*ls\n",
/* Next directory entry. */
pObjDir++;
}
}
/*
* Clean up and return.
*/
}
/**
* Tries to open VBoxDrvErrorInfo and read extra error info from it.
*
* @returns pszErrorInfo.
* @param pszErrorInfo The destination buffer. Will always be
* terminated.
* @param cbErrorInfo The size of the destination buffer.
* @param pszPrefix What to prefix the error info with, if we got
* anything.
*/
DECLHIDDEN(char *) supR3HardenedWinReadErrorInfoDevice(char *pszErrorInfo, size_t cbErrorInfo, const char *pszPrefix)
{
/*
* Try open the device.
*/
InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
if (NT_SUCCESS(rcNt))
{
/*
* Try read error info.
*/
{
if (NT_SUCCESS(rcNt))
{
}
else
{
*pszErrorInfo = '\0';
if (rcNt != STATUS_END_OF_FILE)
}
}
else
}
else
return pszErrorInfo;
}
/**
* Checks if the driver exists.
*
* This checks whether the driver is present in the /Driver object directory.
* Drivers being initialized or terminated will have an object there
*
* @returns true if it exists, false if not.
* @param pszDriver The driver name.
*/
static bool supR3HardenedWinDriverExists(const char *pszDriver)
{
/*
* Open the driver object directory.
*/
InitializeObjectAttributes(&ObjAttr, &NtDirName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
#ifdef VBOX_STRICT
#endif
if (!NT_SUCCESS(rcNt))
return true;
/*
* Enumerate it, looking for the driver.
*/
bool fFound = true;
ULONG uObjDirCtx = 0;
do
{
FALSE /*ReturnSingleEntry */,
FALSE /*RestartScan*/,
&cbActual);
break;
{
{
fFound = true;
break;
}
/* Next directory entry. */
pObjDir++;
}
} while (!fFound);
/*
* Clean up and return.
*/
return fFound;
}
/**
* Open the stub device before the 2nd respawn.
*/
static void supR3HardenedWinOpenStubDevice(void)
{
if (g_fSupStubOpened)
return;
/*
* Retry if we think driver might still be initializing (STATUS_NO_SUCH_DEVICE + \Drivers\VBoxDrv).
*/
{
InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
/* The STATUS_NO_SUCH_DEVICE might be returned if the device is not
completely initialized. Delay a little bit and try again. */
if (rcNt != STATUS_NO_SUCH_DEVICE)
break;
break;
if (!supR3HardenedWinDriverExists("VBoxDrv"))
{
/** @todo Consider starting the VBoxdrv.sys service. Requires 2nd process
* though, rather complicated actually as CreateProcess causes all
* kind of things to happen to this process which would make it hard to
* pass the process verification tests... :-/ */
break;
}
if (iTry < 8)
else
}
if (NT_SUCCESS(rcNt))
g_fSupStubOpened = true;
else
{
/*
* Report trouble (fatal). For some errors codes we try gather some
* extra information that goes into VBoxStartup.log so that we stand a
* better chance resolving the issue.
*/
char szErrorInfo[_4K];
int rc = VERR_OPEN_FAILED;
{
/*
* \Windows\ApiPort open trouble. So far only
* STATUS_OBJECT_TYPE_MISMATCH has been observed.
*/
if (rc == VERR_SUPDRV_APIPORT_OPEN_ERROR)
{
SUP_DPRINTF(("Error opening VBoxDrvStub: VERR_SUPDRV_APIPORT_OPEN_ERROR\n"));
char szDir[64];
if (uSessionId == 0)
else
{
}
supR3HardenedWinLogObjDir("\\Windows");
supR3HardenedWinLogObjDir("\\Sessions");
"NtCreateFile(%ls) failed: VERR_SUPDRV_APIPORT_OPEN_ERROR\n"
"\n"
"Error getting %s\\ApiPort in the driver from vboxdrv.\n"
"\n"
"Could be due to security software is redirecting access to it, so please include full "
"details of such software in a bug report. VBoxStartup.log may contain details important "
"to resolving the issue.%s"
"\n\nVBoxDrvStub error: "));
}
/*
* Generic VBox failure message.
*/
"\nVBoxDrvStub error: "));
}
else
{
const char *pszDefine;
switch (rcNt)
{
default: pszDefine = ""; break;
}
/*
* Problems opening the device is generally due to driver load/
* unload issues. Check whether the driver is loaded and make
* suggestions accordingly.
*/
/** @todo don't fail during early init, wait till later and try load the driver if missing or at least query the service manager for additional information. */
if ( rcNt == STATUS_NO_SUCH_DEVICE
|| rcNt == STATUS_OBJECT_NAME_NOT_FOUND)
{
if (supR3HardenedWinDriverExists("VBoxDrv"))
"NtCreateFile(%ls) failed: %#x%s (%u retries)\n"
"\n"
"information about its state. Rebooting may actually help.%s"
"\nVBoxDrvStub error: "));
else
"NtCreateFile(%ls) failed: %#x%s (%u retries)\n"
"\n"
"Driver is does not appear to be loaded. Try 'sc.exe start vboxdrv', reinstall "
"VirtualBox or reboot.%s"
"\nVBoxDrvStub error: "));
}
/* Generic NT failure message. */
"NtCreateFile(%ls) failed: %#x%s (%u retries)%s",
"\nVBoxDrvStub error: "));
}
}
}
/**
* Called by the main code if supR3HardenedWinIsReSpawnNeeded returns @c true.
*
* @returns Program exit code.
*/
{
/*
* Before the 2nd respawn we set up a child protection deal with the
* support driver via /Devices/VBoxDrvStub. (We tried to do this
* during the early init, but in case we had trouble accessing vboxdrv we
* retry it here where we have kernel32.dll and others to pull in for
* better diagnostics.)
*/
if (iWhich == 2)
/*
* Make sure we're alone in the stub process before creating the VM process
* and that there isn't any debuggers attached.
*/
if (iWhich == 2)
{
if (RT_SUCCESS(rc))
rc = supHardNtVpThread(NtCurrentProcess(), NtCurrentThread(), RTErrInfoInitStatic(&g_ErrInfoStatic));
if (RT_FAILURE(rc))
supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Integrity, rc, "%s", g_ErrInfoStatic.szMsg);
}
/*
* Respawn the process with kernel protection for the new process.
*/
SUPR3HARDENED_ASSERT(false); /* We're not supposed to get here! */
return RTEXITCODE_FAILURE;
}
/**
* Checks if re-spawning is required, replacing the respawn argument if not.
*
* @returns true if required, false if not. In the latter case, the first
* argument in the vector is replaced.
* @param iWhich Which respawn we're to check for, 1 being the
* first one, and 2 the second and final.
* @param cArgs The number of arguments.
* @param papszArgs Pointer to the argument vector.
*/
{
if (cArgs < 1)
return true;
{
if (iWhich > 1)
return true;
}
{
if (iWhich < 2)
return false;
}
else
return true;
/* Replace the argument. */
return false;
}
/**
* Initializes the windows verficiation bits and other things we're better off
* doing after main() has passed on it's data.
*
* @param fFlags The main flags.
* @param fAvastKludge Whether to apply the avast kludge.
*/
{
#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
/*
* Install a anti debugging hack before we continue. This prevents most
* notifications from ending up in the debugger. (Also applied to the
* child process when respawning.)
*/
if (!NT_SUCCESS(rcNt))
"NtSetInformationThread/ThreadHideFromDebugger failed: %#x\n", rcNt);
#endif
/*
* Init the verifier.
*/
if (RT_FAILURE(rc))
/*
* Get the windows system directory from the KnownDlls dir.
*/
InitializeObjectAttributes(&ObjAttrs, &UniStr, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
if (!NT_SUCCESS(rcNt))
supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, rcNt, "Error opening '%ls': %#x", UniStr.Buffer, rcNt);
if (!NT_SUCCESS(rcNt))
supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, rcNt, "Error querying '%ls': %#x", UniStr.Buffer, rcNt);
if (!(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV))
{
if (fAvastKludge)
{
/*
* Do a self purification to cure avast's weird NtOpenFile write-thru
* change in GetBinaryTypeW change in kernel32. Unfortunately, avast
* uses a system thread to perform the process modifications, which
* means it's hard to make sure it had the chance to make them...
*
* We have to resort to kludge doing yield and sleep fudging for a
* number of milliseconds and schedulings before we can hope that avast
* and similar products have done what they need to do. If we do any
* fixes, we wait for a while again and redo it until we're clean.
*
* This is unfortunately kind of fragile.
*/
{
do
{
cSleeps++;
|| cSleeps < 8);
SUP_DPRINTF(("supR3HardenedWinInit: Startup delay kludge #2/%u: %u ms, %u sleeps\n",
cFixes = 0;
rc = supHardenedWinVerifyProcess(NtCurrentProcess(), NtCurrentThread(), SUPHARDNTVPKIND_SELF_PURIFICATION,
break;
if (!g_fSupAdversaries)
cMsFudge = 512;
/* Log the KiOpPrefetchPatchCount value if available, hoping it might sched some light on spider38's case. */
ULONG cPatchCount = 0;
if (NT_SUCCESS(rcNt))
SUP_DPRINTF(("supR3HardenedWinInit: cFixes=%u g_fSupAdversaries=%#x cPatchCount=%#u\n",
else
SUP_DPRINTF(("supR3HardenedWinInit: cFixes=%u g_fSupAdversaries=%#x\n", cFixes, g_fSupAdversaries));
}
}
/*
* Install the hooks.
*/
}
#ifndef VBOX_WITH_VISTA_NO_SP
/*
* Complain about Vista w/o service pack if we're launching a VM.
*/
if ( !(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV)
"Window Vista without any service pack installed is not supported. Please install the latest service pack.");
#endif
}
/**
* Converts the Windows command line string (UTF-16) to an array of UTF-8
* arguments suitable for passing to main().
*
* @returns Pointer to the argument array.
* @param pawcCmdLine The UTF-16 windows command line to parse.
* @param cwcCmdLine The length of the command line.
* @param pcArgs Where to return the number of arguments.
*/
{
/*
* Convert the command line string to UTF-8.
*/
char *pszCmdLine = NULL;
/*
* Parse the command line, carving argument strings out of it.
*/
int cArgs = 0;
int cArgsAllocated = 4;
char *pszSrc = pszCmdLine;
for (;;)
{
/* skip leading blanks. */
while (suplibCommandLineIsArgSeparator(ch))
if (!ch)
break;
/* Add argument to the vector. */
{
cArgsAllocated *= 2;
}
/* Unquote and unescape the string. */
bool fQuoted = false;
do
{
if (ch == '"')
else
{
unsigned cSlashes = 0;
cSlashes++;
if (ch == '"')
{
while (cSlashes >= 2)
{
cSlashes -= 2;
*pszDst++ = '\\';
}
if (cSlashes)
*pszDst++ = '"';
else
}
else
{
pszSrc--;
while (cSlashes-- > 0)
*pszDst++ = '\\';
}
}
/* Terminate the argument. */
*pszDst = '\0';
if (!ch)
break;
}
return papszArgs;
}
/**
* Logs information about a file from a protection product or from Windows.
*
* The purpose here is to better see which version of the product is installed
* and not needing to depend on the user supplying the correct information.
*
* @param pwszFile The NT path to the file.
* @param fAdversarial Set if from a protection product, false if
* system file.
*/
{
/*
* Open the file.
*/
InitializeObjectAttributes(&ObjAttr, &UniStrName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
&ObjAttr,
&Ios,
NULL /* Allocation Size*/,
NULL /*EaBuffer*/,
0 /*EaLength*/);
if (NT_SUCCESS(rcNt))
if (NT_SUCCESS(rcNt))
{
union
{
} u;
char szTmp[64];
/*
* Print basic file information available via NtQueryInformationFile.
*/
rcNt = NtQueryInformationFile(hFile, &Ios, &u.BasicInfo, sizeof(u.BasicInfo), FileBasicInformation);
{
SUP_DPRINTF((" CreationTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.CreationTime.QuadPart), szTmp, sizeof(szTmp))));
/*SUP_DPRINTF((" LastAccessTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.LastAccessTime.QuadPart), szTmp, sizeof(szTmp))));*/
SUP_DPRINTF((" LastWriteTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.LastWriteTime.QuadPart), szTmp, sizeof(szTmp))));
SUP_DPRINTF((" ChangeTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.ChangeTime.QuadPart), szTmp, sizeof(szTmp))));
}
else
else
/*
* Read the image header and extract the timestamp and other useful info.
*/
RT_ZERO(u);
{
if (offNtHdrs < sizeof(u) - sizeof(IMAGE_NT_HEADERS))
{
{
SUP_DPRINTF((" Image Version: %u.%u\n",
SUP_DPRINTF((" SizeOfImage: %#x (%u)\n", pNtHdrs64->OptionalHeader.SizeOfImage, pNtHdrs64->OptionalHeader.SizeOfImage));
/*
* Very crude way to extract info from the file version resource.
*/
IMAGE_DATA_DIRECTORY RsrcDir = { 0, 0 };
{
{
break;
}
{
RT_ZERO(u);
{
{
MY_WIDE_STR_TUPLE("ProductName"),
MY_WIDE_STR_TUPLE("ProductVersion"),
MY_WIDE_STR_TUPLE("FileVersion"),
MY_WIDE_STR_TUPLE("SpecialBuild"),
MY_WIDE_STR_TUPLE("PrivateBuild"),
MY_WIDE_STR_TUPLE("FileDescription"),
};
{
while (cwcLeft-- > 0)
{
{
{
if (*pwc)
break;
if (RT_SUCCESS(rc))
SUP_DPRINTF((" %ls:%*s %ls",
else
SUP_DPRINTF((" %ls:%*s rc=%Rrc",
break;
}
}
pwc++;
}
}
}
else
}
else
SUP_DPRINTF((" Resource section not found.\n"));
}
}
else
}
else
}
else
}
}
/**
* Scans the Driver directory for drivers which may invade our processes.
*
* @returns Mask of SUPHARDNT_ADVERSARY_XXX flags.
*
* @remarks The enumeration of \Driver normally requires administrator
* privileges. So, the detection we're doing here isn't always gonna
* work just based on that.
*
* @todo Find drivers in \FileSystems as well, then we could detect VrNsdDrv
* from ViRobot APT Shield 2.0.
*/
static uint32_t supR3HardenedWinFindAdversaries(void)
{
static const struct
{
const char *pszDriver;
} s_aDrivers[] =
{
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SRTSPX" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymDS" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymEvent" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymIRON" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymNetS" },
{ SUPHARDNT_ADVERSARY_AVAST, "aswHwid" },
{ SUPHARDNT_ADVERSARY_AVAST, "aswMonFlt" },
{ SUPHARDNT_ADVERSARY_AVAST, "aswRdr2" },
{ SUPHARDNT_ADVERSARY_AVAST, "aswRvrt" },
{ SUPHARDNT_ADVERSARY_AVAST, "aswSnx" },
{ SUPHARDNT_ADVERSARY_AVAST, "aswsp" },
{ SUPHARDNT_ADVERSARY_AVAST, "aswStm" },
{ SUPHARDNT_ADVERSARY_AVAST, "aswVmm" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, "tmcomm" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, "tmactmon" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, "tmevtmgr" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, "tmtdi" },
{ SUPHARDNT_ADVERSARY_MCAFEE, "cfwids" },
{ SUPHARDNT_ADVERSARY_MCAFEE, "McPvDrv" },
{ SUPHARDNT_ADVERSARY_MCAFEE, "mfeapfk" },
{ SUPHARDNT_ADVERSARY_MCAFEE, "mfeavfk" },
{ SUPHARDNT_ADVERSARY_MCAFEE, "mfefirek" },
{ SUPHARDNT_ADVERSARY_MCAFEE, "mfehidk" },
{ SUPHARDNT_ADVERSARY_MCAFEE, "mfencbdc" },
{ SUPHARDNT_ADVERSARY_MCAFEE, "mfewfpk" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, "kl1" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, "klflt" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, "klif" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, "KLIM6" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, "klkbdflt" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, "klmouflt" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, "kltdi" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, "kneps" },
{ SUPHARDNT_ADVERSARY_MBAM, "MBAMWebAccessControl" },
{ SUPHARDNT_ADVERSARY_MBAM, "mbam" },
{ SUPHARDNT_ADVERSARY_MBAM, "mbamchameleon" },
{ SUPHARDNT_ADVERSARY_MBAM, "mwav" },
{ SUPHARDNT_ADVERSARY_MBAM, "mbamswissarmy" },
{ SUPHARDNT_ADVERSARY_AVG, "avgfwfd" },
{ SUPHARDNT_ADVERSARY_AVG, "avgtdia" },
{ SUPHARDNT_ADVERSARY_PANDA, "PSINAflt" },
{ SUPHARDNT_ADVERSARY_PANDA, "PSINFile" },
{ SUPHARDNT_ADVERSARY_PANDA, "PSINKNC" },
{ SUPHARDNT_ADVERSARY_PANDA, "PSINProc" },
{ SUPHARDNT_ADVERSARY_PANDA, "PSINProt" },
{ SUPHARDNT_ADVERSARY_PANDA, "PSINReg" },
{ SUPHARDNT_ADVERSARY_PANDA, "PSKMAD" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSAlpc" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSHttp" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNShttps" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSIds" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSNAHSL" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSpicc" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSPihsw" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSPop3" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSProt" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSPrv" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSSmtp" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNSStrm" },
{ SUPHARDNT_ADVERSARY_PANDA, "NNStlsc" },
{ SUPHARDNT_ADVERSARY_MSE, "NisDrv" },
/*{ SUPHARDNT_ADVERSARY_COMODO, "cmdguard" }, file system */
{ SUPHARDNT_ADVERSARY_COMODO, "inspect" },
{ SUPHARDNT_ADVERSARY_COMODO, "cmdHlp" },
};
static const struct
{
} s_aFiles[] =
{
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\SysPlant.sys" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\sysfer.dll" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\sysferThunk.dll" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\ccsetx64.sys" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\ironx64.sys" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\srtsp64.sys" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\srtspx64.sys" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symds64.sys" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symefa64.sys" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symelam.sys" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symnets.sys" },
{ SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\symevent64x86.sys" },
{ SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswHwid.sys" },
{ SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswMonFlt.sys" },
{ SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswRdr2.sys" },
{ SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswRvrt.sys" },
{ SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswSnx.sys" },
{ SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswsp.sys" },
{ SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswStm.sys" },
{ SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswVmm.sys" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmcomm.sys" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmactmon.sys" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmevtmgr.sys" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmtdi.sys" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmebc64.sys" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmeevw.sys" },
{ SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmciesc.sys" },
{ SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\cfwids.sys" },
{ SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\McPvDrv.sys" },
{ SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfeapfk.sys" },
{ SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfeavfk.sys" },
{ SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfefirek.sys" },
{ SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfehidk.sys" },
{ SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfencbdc.sys" },
{ SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfewfpk.sys" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\kl1.sys" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klflt.sys" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klif.sys" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klim6.sys" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klkbdflt.sys" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klmouflt.sys" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\kltdi.sys" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\kneps.sys" },
{ SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\klfphc.dll" },
{ SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\MBAMSwissArmy.sys" },
{ SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\mwac.sys" },
{ SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\mbamchameleon.sys" },
{ SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\mbam.sys" },
{ SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgrkx64.sys" },
{ SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgmfx64.sys" },
{ SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgidsdrivera.sys" },
{ SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgidsha.sys" },
{ SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgtdia.sys" },
{ SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgloga.sys" },
{ SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgldx64.sys" },
{ SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgdiska.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINAflt.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINFile.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINKNC.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINProc.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINProt.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINReg.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSKMAD.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSAlpc.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSHttp.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNShttps.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSIds.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSNAHSL.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSpicc.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSPihsw.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSPop3.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSProt.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSPrv.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSSmtp.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSStrm.sys" },
{ SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNStlsc.sys" },
{ SUPHARDNT_ADVERSARY_MSE, L"\\SystemRoot\\System32\\drivers\\MpFilter.sys" },
{ SUPHARDNT_ADVERSARY_MSE, L"\\SystemRoot\\System32\\drivers\\NisDrvWFP.sys" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cmdguard.sys" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cmderd.sys" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\inspect.sys" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cmdhlp.sys" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cfrmd.sys" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\hmd.sys" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\guard64.dll" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\cmdvrt64.dll" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\cmdkbd64.dll" },
{ SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\cmdcsr.dll" },
{ SUPHARDNT_ADVERSARY_ZONE_ALARM, L"\\SystemRoot\\System32\\drivers\\vsdatant.sys" },
{ SUPHARDNT_ADVERSARY_ZONE_ALARM, L"\\SystemRoot\\System32\\AntiTheftCredentialProvider.dll" },
};
/*
* Open the driver object directory.
*/
InitializeObjectAttributes(&ObjAttr, &NtDirName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
#ifdef VBOX_STRICT
#endif
if (NT_SUCCESS(rcNt))
{
/*
* Enumerate it, looking for the driver.
*/
ULONG uObjDirCtx = 0;
for (;;)
{
FALSE /*ReturnSingleEntry */,
FALSE /*RestartScan*/,
&cbActual);
break;
{
{
break;
}
/* Next directory entry. */
pObjDir++;
}
}
}
else
/*
* Look for files.
*/
{
InitializeObjectAttributes(&ObjAttr, &UniStrName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
rcNt = NtCreateFile(&hFile, GENERIC_READ, &ObjAttr, &Ios, NULL /* Allocation Size*/, FILE_ATTRIBUTE_NORMAL,
{
}
}
/*
* Log details.
*/
return fFound;
}
/**
* The executable entry point.
*
* This is normally taken care of by the C runtime library, but we don't want to
* get involved with anything as complicated like the CRT in this setup. So, we
* it everything ourselves, including parameter parsing.
*/
{
/*
* Initialize the NTDLL API wrappers. This aims at bypassing patched NTDLL
* in all the processes leading up the VM process.
*/
/*
* Notify the parent process that we're probably capable of reporting our
* own errors.
*/
{
}
else
/*
* After having resolved imports we patch the LdrInitializeThunk code so
* that it's more difficult to invade our privacy by CreateRemoteThread.
* We'll re-enable this after opening the driver or temporarily while respawning.
*/
/*
* Init g_uNtVerCombined. (The code is shared with SUPR3.lib and lives in
*/
/*
* Convert the arguments to UTF-8 and open the log file if specified.
* This must be done as early as possible since the code below may fail.
*/
int cArgs;
char **papszArgs = suplibCommandLineToArgvWStub(pCmdLineStr->Buffer, pCmdLineStr->Length / sizeof(WCHAR), &cArgs);
/*
* Log information about important system files.
*/
/*
* Scan the system for adversaries, logging information about them.
*/
/*
* Get the executable name.
*/
"The executable path is too long.");
/* The NT version. */
HANDLE hFile = CreateFileW(g_wszSupLibHardenedExePath, GENERIC_READ, FILE_SHARE_READ, NULL /*pSecurityAttributes*/,
supR3HardenedFatalMsg("suplibHardenedWindowsMain", kSupInitOp_Integrity, RTErrConvertFromWin32(RtlGetLastWin32Error()),
"Error opening the executable: %u (%ls).", RtlGetLastWin32Error());
if (!NT_SUCCESS(rcNt))
supR3HardenedFatalMsg("suplibHardenedWindowsMain", kSupInitOp_Integrity, RTErrConvertFromNtStatus(rcNt),
/* The NT executable name offset / dir path length. */
while ( g_offSupLibHardenedExeNtName > 1
/*
* If we've done early init already, register the DLL load notification
* callback and reinstall the NtDll patches.
*/
{
supR3HardenedWinReInstallHooks(false /*fFirstCall */);
}
/*
* Call the C/C++ main function.
*/
SUP_DPRINTF(("Calling main()\n"));
/*
* Exit the process (never return).
*/
}
/**
* Reports an error to the parent process via the process parameter structure.
*
* @param pszWhere Where this error occured, if fatal message. NULL
* if not message.
* @param enmWhat Which init operation went wrong if fatal
* message. kSupInitOp_Invalid if not message.
* @param rc The status code to report.
* @param pszFormat The format string.
* @param va The format arguments.
*/
DECLHIDDEN(void) supR3HardenedWinReportErrorToParent(const char *pszWhere, SUPINITOP enmWhat, int rc,
{
if (pszWhere)
else
if (NT_SUCCESS(rcNt))
{
}
}
/**
* Routine called by the supR3HardenedEarlyProcessInitThunk assembly routine
* when LdrInitializeThunk is executed in during process initialization.
*
* This initializes the Stub and VM processes, hooking NTDLL APIs and opening
* the device driver before any other DLLs gets loaded into the process. This
* greately reduces and controls the trusted code base of the process compared
* to opening the driver from SUPR3HardenedMain. It also avoids issues with so
* call protection software that is in the habit of patching half of the ntdll
* and kernel32 APIs in the process, making it almost indistinguishable from
* software that is up to no good. Once we've opened vboxdrv, the process
* should be locked down so thighly that only kernel software and csrss can mess
* with the process.
*/
{
/*
* When the first thread gets here we wait for the parent to continue with
* the process purifications. The primary thread must execute for image
* load notifications to trigger, at least in more recent windows versions.
* The old trick of starting a different thread that terminates immediately
* thus doesn't work.
*
* We are not allowed to modify any data at this point because it will be
* reset by the child process purification the parent does when we stop. To
* sabotage thread creation during purification, and to avoid unnecessary
* work for the parent, we reset g_ProcParams before signalling the parent
* here.
*/
{
NtTerminateThread(0, 0);
return 0x22; /* crash */
}
/* Retrieve the data we need. */
if (!RT_VALID_PTR(uNtDllAddr))
{
NtTerminateThread(0, 0);
return 0x23; /* crash */
}
|| hEvtParent == NULL
{
NtTerminateThread(0, 0);
return 0x24; /* crash */
}
/* Resolve the APIs we need. */
/* Signal the parent that we're ready for purification. */
if (rcNt != STATUS_SUCCESS)
return 0x33; /* crash */
/* Wait up to 2 mins for the parent to exorcise evil. */
if (rcNt != STATUS_SUCCESS)
return 0x34; /* crash */
/*
* We're good to go, work global state and restore process parameters.
* Note that we will not restore uNtDllAddr since that is our first defence
* against unwanted threads (see above).
*/
g_fSupEarlyProcessInit = true;
/*
* Initialize the NTDLL imports that we consider usable before the
* process has been initialized.
*/
/*
* Init g_uNtVerCombined as well as we can at this point.
*/
/*
* Convert the arguments to UTF-8 so we can open the log file if specified.
* We may have to normalize the pointer on older windows version (not w7/64 +).
* Note! This leaks memory at present.
*/
int cArgs;
char **papszArgs = suplibCommandLineToArgvWStub(CmdLineStr.Buffer, CmdLineStr.Length / sizeof(WCHAR), &cArgs);
/*
* Set up the direct system calls so we can more easily hook NtCreateSection.
*/
supR3HardenedWinInitSyscalls(true /*fReportErrors*/);
/*
* Determine the executable path and name. Will NOT determine the windows style
* executable path here as we don't need it.
*/
rcNt = NtQueryVirtualMemory(NtCurrentProcess(), &g_ProcParams, MemorySectionName, &g_SupLibHardenedExeNtPath,
if ( !NT_SUCCESS(rcNt)
supR3HardenedFatal("NtQueryVirtualMemory/MemorySectionName failed in supR3HardenedVmProcessInit: %#x\n", rcNt);
/* The NT executable name offset / dir path length. */
while ( g_offSupLibHardenedExeNtName > 1
/*
* Initialize the image verification stuff (hooks LdrLoadDll and NtCreateSection).
*/
supR3HardenedWinInit(0, false /*fAvastKludge*/);
/*
* Open the driver.
*/
{
SUP_DPRINTF(("supR3HardenedVmProcessInit: Opening vboxdrv stub...\n"));
}
{
SUP_DPRINTF(("supR3HardenedVmProcessInit: Opening vboxdrv...\n"));
}
else
/*
* Reinstall the NtDll patches since there is a slight possibility that
* someone undid them while we where busy opening the device.
*/
supR3HardenedWinReInstallHooks(false /*fFirstCall */);
/*
* Restore the LdrInitializeThunk code so we can initialize the process
* normally when we return.
*/
SUP_DPRINTF(("supR3HardenedVmProcessInit: Restoring LdrInitializeThunk...\n"));
if (RT_FAILURE(rc))
supR3HardenedFatal("supR3HardenedVmProcessInit: supHardNtLdrCacheOpen failed on NTDLL: %Rrc\n", rc);
if (RT_FAILURE(rc))
supR3HardenedFatal("supR3HardenedVmProcessInit: supHardNtLdrCacheEntryGetBits failed on NTDLL: %Rrc\n", rc);
rc = RTLdrGetSymbolEx(pLdrEntry->hLdrMod, pbBits, uNtDllAddr, UINT32_MAX, "LdrInitializeThunk", &uValue);
if (RT_FAILURE(rc))
SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pvLdrInitThunk, 16, PAGE_EXECUTE_READWRITE));
SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pvLdrInitThunk, 16, PAGE_EXECUTE_READ));
SUP_DPRINTF(("supR3HardenedVmProcessInit: Returning to LdrInitializeThunk...\n"));
return (uintptr_t)pvLdrInitThunk;
}