SUPR3HardenedMain-win.cpp revision b2560fc359a998cb1002e5de6eba0ef716d48803
/* $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"
/*******************************************************************************
* 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 "81954AF5-4D2F-31EB-A142-B7AF187A1C41-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 "81954AF5-4D2F-31EB-A142-B7AF187A1C41-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;
/** The file handle. */
/** If fIndexNumber is set, this is an file system internal file identifier. */
/** The path hash value. */
/** The verification result. */
int rc;
/** Whether IndexNumber is valid */
bool fIndexNumberValid;
/** cwcPath * sizeof(RTUTF16). */
/** The full path of this entry (variable size). */
/** Pointer to an image verifier path entry. */
typedef VERIFIERCACHEENTRY *PVERIFIERCACHEENTRY;
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/** @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.
* @{ */
/** The jump back address of the patched NtCreateSection. */
/** Pointer to the bit of assembly code that will perform the original
* NtCreateSection operation. */
/** The hash table of verifier cache . */
/** @ */
/** Static error info structure used during init. */
static RTERRINFOSTATIC g_ErrInfoStatic;
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
#ifdef RT_ARCH_AMD64
# include "NtCreateSection-template-amd64-syscall-type-1.h"
#endif
#ifdef RT_ARCH_X86
# include "NtCreateSection-template-x86-syscall-type-1.h"
#endif
/**
* 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++;
}
/**
* Allocate zero filled memory on the heap.
*
* @returns Pointer to the memory. Will never return NULL, triggers a fatal
* error instead.
* @param cb The number of bytes to allocate.
*/
{
if (!pv)
return pv;
}
/**
* Reallocates memory on the heap.
*
* @returns Pointer to the resized memory block. Will never return NULL,
* triggers a fatal error instead.
* @param pvOld The old memory block.
* @param cbNew The new block size.
*/
{
if (!pvOld)
return suplibHardenedAllocZ(cbNew);
if (!pv)
return pv;
}
/**
* Frees memory allocated by suplibHardenedAlloc, suplibHardenedAllocZ or
* suplibHardenedReAlloc.
*
* @param pv Pointer to the memeory to be freed.
*/
{
if (pv)
}
/**
* 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
&& GetLastError() == ERROR_INVALID_PARAMETER)
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 string.
*
* @returns Hash value.
* @param pUniStr String to hash.
*/
{
while (cwcLeft-- > 0)
{
}
return uHash;
}
/**
* 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 fCacheable Whether this is a cacheable result. Passed in
* here instead of being handled by the caller to
* save code duplication.
*/
static void supR3HardenedWinVerifyCacheInsert(PCUNICODE_STRING pUniStr, HANDLE hFile, int rc, bool fCacheable)
{
/*
* Don't cache anything until we've got the WinVerifyTrust API up and running.
*/
&& fCacheable)
{
/*
* Allocate and initalize a new entry.
*/
if (pEntry)
{
/*
* Try insert it, careful with concurrent code as well as potential duplicates.
*/
for (;;)
{
return;
if (!pOther)
continue;
break;
}
/* Duplicate entry. */
#ifdef DEBUG_bird
__debugbreak();
#endif
}
}
}
/**
* 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;
}
/**
* 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 */
}
}
/**
* 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
{
/*
* 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,
"supR3HardenedMonitor_NtCreateSection: NtQueryObject -> %#x (fImage=%d fExecMap=%d fExecProt=%d)\n",
return rcNt;
}
{
}
/*
* Check the cache.
*/
if (pCacheHit)
{
SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: cache hit (%Rrc) on %ls\n", pCacheHit->rc, pCacheHit->wszPath));
return g_pfnNtCreateSectionReal(phSection, fAccess, pObjAttribs, pcbSection, fProtect, fAttribs, hFile);
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedMonitor_NtCreateSection: cached rc=%Rrc fImage=%d fExecMap=%d fExecProt=%d %ls\n",
return STATUS_TRUST_FAILURE;
}
/*
* On XP the loader might hand us handles with just FILE_EXECUTE and
* SYNCRHONIZE, the means reading will fail later on. So, we might
* have to reopen the file here in order to validate it - annoying.
*/
&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,
"supR3HardenedMonitor_NtCreateSection: Failed to duplicate and open the file: rcNt=%#x hFile=%p %ls\n",
return rcNt;
}
}
else
{
#ifdef DEBUG
supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_NtCreateSection: NtDuplicateObject(,%#x,) failed: %#x\n", hFile, rcNt);
#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(("supR3HardenedMonitor_NtCreateSection: Applying the drop-exec-kludge for '%ls'\n", uBuf.UniStr.Buffer));
if (fAccess & SECTION_MAP_EXECUTE)
if (fProtect & PAGE_EXECUTE)
return g_pfnNtCreateSectionReal(phSection, fAccess, pObjAttribs, pcbSection, fProtect, fAttribs, hFile);
}
}
/*
* Check the path. We don't allow DLLs to be loaded from just anywhere:
* 1. System32 - normal code or cat signing.
* 2. WinSxS - normal code or cat signing.
* 3. VirtualBox - kernel code signing and integrity checks.
*/
bool fSystem32 = false;
{
fSystem32 = true;
}
g_offSupLibHardenedExeNtName * sizeof(WCHAR)) == 0)
#ifdef VBOX_PERMIT_MORE
#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),
{
return g_pfnNtCreateSectionReal(phSection, fAccess, pObjAttribs, pcbSection, fProtect, fAttribs, hFile);
}
#endif
else
{
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedMonitor_NtCreateSection: Not a trusted location: '%ls' (fImage=%d fExecMap=%d fExecProt=%d)\n",
return STATUS_TRUST_FAILURE;
}
/*
* Do the verification. For better error message we borrow what's
* left of the path buffer for an RTERRINFO buffer.
*/
bool fCacheable = true;
int rc = supHardenedWinVerifyImageByHandle(hMyFile, uBuf.UniStr.Buffer, fFlags, &fCacheable, &ErrInfo);
if (RT_FAILURE(rc))
{
supR3HardenedError(VINF_SUCCESS, false,
"supR3HardenedMonitor_NtCreateSection: rc=%Rrc fImage=%d fExecMap=%d fExecProt=%d %ls: %s\n",
return STATUS_TRUST_FAILURE;
}
}
}
/*
* Call checked out OK, call the original.
*/
return g_pfnNtCreateSectionReal(phSection, fAccess, pObjAttribs, pcbSection, fProtect, fAttribs, hFile);
}
#ifdef RT_ARCH_AMD64
/**
* Tries to allocate memory between @a uStart and @a uEnd.
*
* @returns Pointer to the memory on success. NULL on failure.
* @param uStart The start address.
* @param uEnd The end address. This is lower than @a uStart
* if @a iDirection is negative, and higher if
* positive.
* @param iDirection The search direction.
* @param cbAlloc The number of bytes to allocate.
*/
static void *supR3HardenedWinAllocHookMemory(uintptr_t uStart, uintptr_t uEnd, intptr_t iDirection, size_t cbAlloc)
{
/*
* Make uEnd the last valid return address.
*/
if (iDirection > 0)
{
}
else
/*
* Search for free memory.
*/
for (;;)
{
/*
* Examine the memory at this address, if it's free, try make the allocation here.
*/
(void *)uCur,
&MemInfo,
sizeof(MemInfo),
&cbIgn));
{
for (;;)
{
if (NT_SUCCESS(rcNt))
{
if ( iDirection > 0
return pvMem;
}
/* Advance within the free area and try again? */
if ( iDirection > 0
break;
}
}
/*
* Advance to the next memory region.
*/
if (iDirection > 0)
{
break;
}
else
{
break;
}
}
return NULL;
}
#endif
/**
* 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.
*/
DECLHIDDEN(void) supR3HardenedWinInstallHooks(void)
{
#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
/*
* Install a anti debugging hack before we continue. This prevents most
* notifications from ending up in the debugger.
*/
if (!NT_SUCCESS(rcNt))
"NtSetInformationThread/ThreadHideFromDebugger failed: %#x\n", rcNt);
#endif
/*
* 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 routine.
*/
#ifdef RT_ARCH_AMD64
/*
* For 64-bit hosts we need some memory within a +/-2GB range of the
* actual function to be able to patch it.
*/
-1, cbMem);
if (!pvMem)
{
1, cbMem);
if (!pvMem)
"Failed to allocate memory within the +/-2GB range from NTDLL.\n");
}
/*
* 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 */
/* b8 22 35 ed 0 48 63 c0 ff e0 c3 f 1f 44 0 0 - necros2 - agnitum firewall? */
)
{
switch (pbNtCreateSection[4])
{
# define SYSCALL(a_Num) case a_Num: pfnCallReal = RT_CONCAT(supR3HardenedJmpBack_NtCreateSection_,a_Num); break;
# include "NtCreateSection-template-amd64-syscall-type-1.h"
}
}
if (pfnCallReal)
{
pbNtCreateSection[0] = 0xff;
*(uint32_t *)&pbNtCreateSection[2] = (uint32_t)((uintptr_t)puJmpTab - (uintptr_t)&pbNtCreateSection[2+4]);
return;
}
#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
Note! One nice thing here is that we can share code pattern #1. */
)
)
{
{
# define SYSCALL(a_Num) case a_Num: pfnCallReal = RT_CONCAT(supR3HardenedJmpBack_NtCreateSection_,a_Num); break;
# include "NtCreateSection-template-x86-syscall-type-1.h"
}
}
if (pfnCallReal)
{
pbNtCreateSection[0] = 0xe9;
return;
}
#endif
"Failed to install NtCreateSection 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
,
}
/**
* Verifies the process integrity.
*/
DECLHIDDEN(void) supR3HardenedWinVerifyProcess(void)
{
if (RT_FAILURE(rc))
}
/**
* 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 supR3HardenedGetUserAndLogSids(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 supR3HardenedInitSecAttrs(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.
*/
PSECURITY_DESCRIPTOR pSecDesc = (PSECURITY_DESCRIPTOR)suplibHardenedAllocZ(SECURITY_DESCRIPTOR_MIN_LENGTH);
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);
PRTUTF16 pwszCmdLine = (PRTUTF16)HeapAlloc(GetProcessHeap(), 0 /* dwFlags*/, (cwcCmdLine + 1) * sizeof(RTUTF16));
/*
* 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;
}
/*
* Child-Process Purification - release it from dubious influences.
*
* 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
* matching half of NTDLL or messing with the import table of the
* process executable.
*/
typedef struct SUPR3HARDNTPUCH
{
/** Process handle. */
/** Primary thread handle. */
/** Error buffer. */
/** The address of NTDLL in the child. */
/** The address of NTDLL in this process. */
/** The basic process info. */
/** The probable size of the PEB. */
/** The pristine process environment block. */
typedef SUPR3HARDNTPUCH *PSUPR3HARDNTPUCH;
{
/*
* 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))
return RTErrInfoSetF(pThis->pErrInfo, VERR_GENERAL_FAILURE, "NtWriteVirtualMemory/Peb failed: %#x", rcNt);
return VINF_SUCCESS;
}
/**
* Trigger the initial image events without actually initializing the process.
*
* This is a trick to force sysplant.sys to call its hand by tripping the image
* loaded event for the main executable and ntdll images. This will happen when
* the first thread in a process starts executing in PspUserThreadStartup. We
* create a second thread that quits immediately by means of temporarily
* replacing ntdll!LdrInitializeThunk by a NtTerminateThread call.
* (LdrInitializeThunk is called by way of an APC queued the thread is created,
* thus NtSetContextThread is of no use.)
*
* @returns VBox status code.
* @param pThis The child cleanup
* @param pErrInfo For extended error information.
*/
{
PVOID pvLdrInitThunk = (PVOID)((uintptr_t)LdrInitializeThunk + pThis->uNtDllAddr - pThis->uNtDllParentAddr);
PVOID pvNtTerminateThread = (PVOID)((uintptr_t)NtTerminateThread + pThis->uNtDllAddr - pThis->uNtDllParentAddr);
SUP_DPRINTF(("supR3HardNtPuChTriggerInitialImageEvents: pvLdrInitThunk=%p pvNtTerminateThread=%p\n",
/*
* Back up the thunk code.
*/
NTSTATUS rcNt = NtReadVirtualMemory(pThis->hProcess, pvLdrInitThunk, abBackup, sizeof(abBackup), &cbIgnored);
if (!NT_SUCCESS(rcNt))
"NtReadVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
/*
* Cook up replacement code that calls NtTerminateThread.
*/
#ifdef RT_ARCH_AMD64
*(int32_t *)&abReplacement[5] = (int32_t)((intptr_t)pvNtTerminateThread - ((intptr_t)pvLdrInitThunk + 9));
#elif defined(RT_ARCH_X86)
*(int32_t *)&abReplacement[5] = (int32_t)((intptr_t)pvNtTerminateThread - ((intptr_t)pvLdrInitThunk + 9));
#else
# error "Unsupported arch."
#endif
/*
* Install the replacment code.
*/
rcNt = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, PAGE_EXECUTE_READWRITE, &fOldProt);
if (!NT_SUCCESS(rcNt))
"NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
rcNt = NtWriteVirtualMemory(pThis->hProcess, pvLdrInitThunk, abReplacement, sizeof(abReplacement), &cbIgnored);
if (!NT_SUCCESS(rcNt))
"NtWriteVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
/*
* Create the thread, waiting 10 seconds for it to complete.
*/
NULL /* SecurityAttribs */,
FALSE /* CreateSuspended */,
0 /* ZeroBits */,
0 /* MaximumStackSize */,
0 /* CommittedStackSize */,
NULL /*Parameter*/ ,
&hThread2,
&Thread2Id);
if (NT_SUCCESS(rcNt))
{
}
/*
* Restore the original thunk code and protection.
*/
rcNt = NtWriteVirtualMemory(pThis->hProcess, pvLdrInitThunk, abBackup, sizeof(abBackup), &cbIgnored);
if (!NT_SUCCESS(rcNt))
"NtWriteVirtualMemory/LdrInitializeThunk[restore] failed: %#x", rcNt);
cbProt = 16;
if (!NT_SUCCESS(rcNt))
"NtProtectVirtualMemory/LdrInitializeThunk[restore] failed: %#x", rcNt);
return VINF_SUCCESS;
}
#if 0
static int supR3HardenedWinScratchChildMemory(HANDLE hProcess, void *pv, size_t cb, const char *pszWhat, PRTERRINFO pErrInfo)
{
if (!NT_SUCCESS(rcNt))
return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE, "NtProtectVirtualMemory/%s (%p LB %#zx) failed: %#x",
return VINF_SUCCESS;
}
#endif
{
/*
* 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))
return RTErrInfoSetF(pThis->pErrInfo, VERR_GENERAL_FAILURE, "NtWriteVirtualMemory/Peb failed: %#x", rcNt);
return VINF_SUCCESS;
}
{
{
{
return NULL;
}
}
if (cbBuf >= sizeof(IMAGE_NT_HEADERS))
{
return pNtHdrs;
}
return NULL;
}
#ifdef DEBUG
{
off++;
return off;
}
#endif
{
NTSTATUS rcNt = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, PAGE_READWRITE, &fOldProt);
if (NT_SUCCESS(rcNt))
{
NTSTATUS rcNt2 = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, fCorrectProtection, &fOldProt);
if (NT_SUCCESS(rcNt))
}
return rcNt;
}
{
/*
* Get the image name.
*/
union
{
} uBuf;
&uBuf,
&cbActual);
if (!NT_SUCCESS(rcNt))
SUP_DPRINTF(("supR3HardNtPuChSanitizeImage: %p '%ls'\n", pMemInfo->BaseAddress, uBuf.UniStr.Buffer));
/*
* Open the file.
*/
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))
/*
* Read the headers, ASSUMES the stub isn't pushing the optional header out
* of a 4KB buffer. Also ASSUMEs that the file is more than 4KB in size.
*/
int rc;
if (NT_SUCCESS(rcNt))
if (NT_SUCCESS(rcNt))
{
if (pNtFile)
{
/*
* Read the first 4KB of the process memory.
*/
rcNt = NtReadVirtualMemory(pThis->hProcess, pMemInfo->BaseAddress, abProc, sizeof(abProc), &cbActualMem);
if (NT_SUCCESS(rcNt))
{
rc = VINF_SUCCESS;
else
{
SUP_DPRINTF(("supR3HardNtPuChSanitizeImage: Header diff @%#x in ('%ls')\n",
rc = supR3HardNtPuChRestoreImageBits(pThis, pMemInfo->BaseAddress, abFile, cbCompare, PAGE_READONLY);
}
}
else
"NtReadVirtualMemory returned %#x read 4KB at %p ('%ls').", rcNt,
}
else
}
else
return rc;
}
{
/*
*/
uint32_t cXpExceptions = 0;
for (uint32_t i = 0; i < 1024; i++)
{
MEMORY_BASIC_INFORMATION MemInfo = { 0, 0, 0, 0, 0, 0, 0 };
(void const *)uPtrWhere,
&MemInfo,
sizeof(MemInfo),
&cbActual);
if (!NT_SUCCESS(rcNt))
break;
//SUP_DPRINTF(("supR3HardNtPuChSanitizeMemory: %p (%p LB %#zx): type=%#010x prot=%#06x state=%#07x aprot=%#06x abase=%p\n",
// uPtrWhere, MemInfo.BaseAddress, MemInfo.RegionSize,MemInfo.Type,
// MemInfo.Protect, MemInfo.State, MemInfo.AllocationBase, MemInfo.AllocationProtect));
{
/*
* Restore modified parts of the image from file.
*/
{
if (RT_FAILURE(rc))
return rc;
}
}
/*
* Executable memory outside an image is evil by definition.
*/
else if (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
{
/*
* XP, W2K3 exception: Ignore the CSRSS read-only region as best we can.
*/
if ( (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
&& cXpExceptions == 0
/* && MemInfo.BaseAddress == pPeb->ReadOnlySharedMemoryBase */
else
{
/*
* Free any private executable memory (sysplant.sys allocates executable memory).
*/
{
SUP_DPRINTF(("supR3HardNtPuChSanitizeMemory: Freeing exec mem at %p (%p LB %#zx)\n",
if (!NT_SUCCESS(rcNt))
"NtFreeVirtualMemory (%p LB %#zx) failed: %#x",
}
/*
* Unmap mapped memory, failing that, drop exec privileges.
*/
{
SUP_DPRINTF(("supR3HardNtPuChSanitizeMemory: Unmapping exec mem at %p (%p/%p LB %#zx)\n",
if (!NT_SUCCESS(rcNt))
{
if (!NT_SUCCESS(rcNt2))
if (!NT_SUCCESS(rcNt2))
"NtUnmapViewOfSection (%p/%p LB %#zx) failed: %#x (%#x)",
}
}
else
"Unknown executable memory type %#x at %p/%p LB %#zx",
}
#endif
}
/*
* Advance.
*/
break;
}
return VINF_SUCCESS;
}
{
/*
* 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))
{
{
"ntdll.dll") == 0)
{
SUP_DPRINTF(("supR3HardNtPuChFindNtdll: uNtDllParentAddr=%p uNtDllChildAddr=%p\n",
return;
}
}
}
}
}
/*
* Advance.
*/
break;
}
#ifdef DEBUG
#endif
}
{
/*
* Initialize the purifier instance data.
*/
if (!NT_SUCCESS(rcNt))
"NtQueryInformationProcess/ProcessBasicInformation failed: %#x", rcNt);
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(("supR3HardenedWinPurifyChild: PebBaseAddress=%p cbPeb=%#x\n", This.BasicInfo.PebBaseAddress, This.cbPeb));
rcNt = NtReadVirtualMemory(hProcess, This.BasicInfo.PebBaseAddress, &This.Peb, sizeof(This.Peb), &cbActualMem);
if (!NT_SUCCESS(rcNt))
/*
* Do the work.
*/
if (RT_SUCCESS(rc))
if (RT_SUCCESS(rc))
if (RT_SUCCESS(rc))
return rc;
}
/**
* 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.
*
* @todo Split up this function.
*/
static int supR3HardenedWinDoReSpawn(int iWhich)
{
/*
* 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'",
GetLastError(), pwszCmdLine);
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
/*
* Clean up the process.
*/
if (RT_FAILURE(rc))
{
}
/*
* Start the process execution.
*/
ULONG cSuspendCount = 0;
/*
* 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.
*/
else
fRights, 0 /*HandleAttributes*/, 0);
if (rcNt == STATUS_ACCESS_DENIED)
SYNCHRONIZE, 0 /*HandleAttributes*/, 0);
if (!NT_SUCCESS(rcNt))
{
/* Failure is unacceptable, kill the process. */
supR3HardenedError(rcNt, false /*fFatal*/, "NtDuplicateObject failed on child process handle: %#x\n", rcNt);
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: rcNt=%u rcNtWait=%u hProcess=%p\n",
}
"NtDuplicateObject failed on child process handle: %#x\n", rcNt);
}
/*
* If this is the middle process, wait for both parent and child to quit.
*/
if (iWhich > 1)
{
rcNt = NtQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
if (NT_SUCCESS(rcNt))
{
}
#ifdef DEBUG
#endif
}
{
for (;;)
{
rcNt = NtWaitForMultipleObjects(2, &ahHandles[0], WaitAnyObject, TRUE /*Alertable*/, NULL /*pTimeout*/);
if ( rcNt == STATUS_WAIT_0
|| rcNt == STATUS_ABANDONED_WAIT_0
break;
if ( rcNt != STATUS_TIMEOUT
&& rcNt != STATUS_USER_APC
&& rcNt != STATUS_ALERTED)
}
}
else
{
/*
* Wait for the process 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(("supR3HardenedWinDoReSpawn(%d): Quitting: ExitCode=%#x rcNt=%#x\n", BasicInfo.ExitStatus, rcNt));
}
/**
* 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)
{
/*
* 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))
{
int rc = VERR_OPEN_FAILED;
else
{
const char *pszDefine;
switch (rcNt)
{
default: pszDefine = ""; break;
}
}
}
}
/**
* 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.
*/
if (iWhich == 2)
/*
* Respawn the process with kernel protection for the new process.
*/
return supR3HardenedWinDoReSpawn(iWhich);
}
/**
* 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.
* @param fFlags The main flags.
*/
{
if (RT_FAILURE(rc))
if (!(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV))
#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;
}
/**
* 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.
*/
{
/*
* 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);
/*
* 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(GetLastError()),
"Error opening the executable: %u (%ls).", GetLastError());
if (!NT_SUCCESS(rcNt))
supR3HardenedFatalMsg("suplibHardenedWindowsMain", kSupInitOp_Integrity, RTErrConvertFromNtStatus(rcNt),
/* The NT executable name offset / dir path length. */
while ( g_offSupLibHardenedExeNtName > 1
/*
* Call the C/C++ main function.
*/
SUP_DPRINTF(("Calling main()\n"));
/*
* Exit the process (never return).
*/
}