This commit is contained in:
DavidXanatos 2022-06-05 13:02:46 +02:00
parent 8daec502fb
commit c30ec207c3
59 changed files with 779 additions and 276 deletions

View File

@ -4,6 +4,18 @@ This project adheres to [Semantic Versioning](http://semver.org/).
## [1.2.0 / 5.57.0] - 2022-01-??
### Added
- Reenginiered "SandboxieLogon=y" and set it on by default, now every sandbox gets its own SID
-- Note: this enforces the isolation of individual sandboxes from each other.
### Changed
- reworked hook management, now unloaded dll'f are properly unhooked [#1243](https://github.com/sandboxie-plus/Sandboxie/issues/1243)
## [1.1.1 / 5.56.1] - 2022-05-30 ## [1.1.1 / 5.56.1] - 2022-05-30

View File

@ -131,9 +131,9 @@ BOOLEAN InitHook( HINSTANCE hSbieDll )
{ {
if (hSbieDll) if (hSbieDll)
{ {
HMODULE hAdvapi32 = GetModuleHandle(L"Advapi32.dll"); HMODULE module = GetModuleHandle(L"Advapi32.dll");
void *OpenProcessToken = (P_OpenProcessToken)GetProcAddress(hAdvapi32, "OpenProcessToken"); void *OpenProcessToken = (P_OpenProcessToken)GetProcAddress(module, "OpenProcessToken");
if (OpenProcessToken) if (OpenProcessToken)
SBIEDLL_HOOK(SboxHostDll_, OpenProcessToken); SBIEDLL_HOOK(SboxHostDll_, OpenProcessToken);

View File

@ -57,7 +57,7 @@ static BOOLEAN IsWindows81 = FALSE;
SourceFunc = (void *)func; \ SourceFunc = (void *)func; \
} \ } \
__sys_##func = \ __sys_##func = \
(ULONG_PTR)SbieDll_Hook(FuncName, SourceFunc, my_##func); \ (ULONG_PTR)SbieDll_Hook(FuncName, SourceFunc, my_##func, KernelBase); \
if (! __sys_##func) \ if (! __sys_##func) \
hook_success = FALSE; \ hook_success = FALSE; \
} }

View File

@ -0,0 +1,150 @@
/*++
Copyright (c) Microsoft Corporation, 1992 -
Module Name:
lsalookupi.h
Abstract:
LSA Policy Lookup internal API
--*/
#ifndef _LSALOOKUPI_
#define _LSALOOKUPI_
#ifdef MIDL_PASS
#define SIZE_IS(x) [size_is(x)]
#define SWITCH_IS(x) [switch_is(x)]
#define SWITCH_TYPE(x) [switch_type(x)]
#define CASE(x) [case(x)]
#define RANGE(x,y) [range(x,y)]
#define VAR_SIZE_ARRAY
#define SID_POINTER PISID
#define REF [ref]
#else
#define SIZE_IS(x)
#define SWITCH_IS(x)
#define SWITCH_TYPE(x)
#define CASE(x)
#define RANGE(x,y) __in_range(x,y)
#define VAR_SIZE_ARRAY (1)
#define SID_POINTER PSID
#define REF
#endif
#ifdef __cplusplus
extern "C" {
#endif
//
// Generic negative values for unknown IDs, inapplicable indices etc.
//
#define LSA_UNKNOWN_ID ((ULONG) 0xFFFFFFFFL)
#define LSA_UNKNOWN_INDEX ((LONG) -1)
typedef enum _LSA_SID_NAME_MAPPING_OPERATION_TYPE {
LsaSidNameMappingOperation_Add,
LsaSidNameMappingOperation_Remove,
LsaSidNameMappingOperation_AddMultiple,
} LSA_SID_NAME_MAPPING_OPERATION_TYPE, *PLSA_SID_NAME_MAPPING_OPERATION_TYPE;
#define LSA_MAXIMUM_NUMBER_OF_CHARACTERS_IN_NAMES_FOR_SNMC 0x400
typedef struct _LSA_SID_NAME_MAPPING_OPERATION_ADD_INPUT {
UNICODE_STRING DomainName;
UNICODE_STRING AccountName;
REF SID_POINTER Sid;
ULONG Flags;
} LSA_SID_NAME_MAPPING_OPERATION_ADD_INPUT, *PLSA_SID_NAME_MAPPING_OPERATION_ADD_INPUT;
typedef struct _LSA_SID_NAME_MAPPING_OPERATION_REMOVE_INPUT {
UNICODE_STRING DomainName;
UNICODE_STRING AccountName;
} LSA_SID_NAME_MAPPING_OPERATION_REMOVE_INPUT, *PLSA_SID_NAME_MAPPING_OPERATION_REMOVE_INPUT;
#define LSA_MAXIMUM_NUMBER_OF_MAPPINGS_IN_ADD_MULTIPLE_INPUT 0x1000
typedef struct _LSA_SID_NAME_MAPPING_OPERATION_ADD_MULTIPLE_INPUT {
RANGE( 1, LSA_MAXIMUM_NUMBER_OF_MAPPINGS_IN_ADD_MULTIPLE_INPUT )
ULONG Count;
REF SIZE_IS( Count ) PLSA_SID_NAME_MAPPING_OPERATION_ADD_INPUT Mappings;
} LSA_SID_NAME_MAPPING_OPERATION_ADD_MULTIPLE_INPUT, *PLSA_SID_NAME_MAPPING_OPERATION_ADD_MULTIPLE_INPUT;
typedef SWITCH_TYPE( LSA_SID_NAME_MAPPING_OPERATION_TYPE ) union _LSA_SID_NAME_MAPPING_OPERATION_INPUT {
CASE( LsaSidNameMappingOperation_Add )
LSA_SID_NAME_MAPPING_OPERATION_ADD_INPUT AddInput;
CASE( LsaSidNameMappingOperation_Remove )
LSA_SID_NAME_MAPPING_OPERATION_REMOVE_INPUT RemoveInput;
CASE( LsaSidNameMappingOperation_AddMultiple )
LSA_SID_NAME_MAPPING_OPERATION_ADD_MULTIPLE_INPUT AddMultipleInput;
} LSA_SID_NAME_MAPPING_OPERATION_INPUT, *PLSA_SID_NAME_MAPPING_OPERATION_INPUT;
typedef enum _LSA_SID_NAME_MAPPING_OPERATION_ERROR {
LsaSidNameMappingOperation_Success,
LsaSidNameMappingOperation_NonMappingError,
LsaSidNameMappingOperation_NameCollision,
LsaSidNameMappingOperation_SidCollision,
LsaSidNameMappingOperation_DomainNotFound,
LsaSidNameMappingOperation_DomainSidPrefixMismatch,
LsaSidNameMappingOperation_MappingNotFound,
} LSA_SID_NAME_MAPPING_OPERATION_ERROR, *PLSA_SID_NAME_MAPPING_OPERATION_ERROR;
typedef struct _LSA_SID_NAME_MAPPING_OPERATION_GENERIC_OUTPUT {
LSA_SID_NAME_MAPPING_OPERATION_ERROR ErrorCode;
} LSA_SID_NAME_MAPPING_OPERATION_GENERIC_OUTPUT, *PLSA_SID_NAME_MAPPING_OPERATION_GENERIC_OUTPUT;
typedef LSA_SID_NAME_MAPPING_OPERATION_GENERIC_OUTPUT LSA_SID_NAME_MAPPING_OPERATION_ADD_OUTPUT, *PLSA_SID_NAME_MAPPING_OPERATION_ADD_OUTPUT;
typedef LSA_SID_NAME_MAPPING_OPERATION_GENERIC_OUTPUT LSA_SID_NAME_MAPPING_OPERATION_REMOVE_OUTPUT, *PLSA_SID_NAME_MAPPING_OPERATION_REMOVE_OUTPUT;
typedef LSA_SID_NAME_MAPPING_OPERATION_GENERIC_OUTPUT LSA_SID_NAME_MAPPING_OPERATION_ADD_MULTIPLE_OUTPUT, *PLSA_SID_NAME_MAPPING_OPERATION_ADD_MULTIPLE_OUTPUT;
typedef SWITCH_TYPE( LSA_SID_NAME_MAPPING_OPERATION_TYPE ) union _LSA_SID_NAME_MAPPING_OPERATION_OUTPUT {
CASE( LsaSidNameMappingOperation_Add )
LSA_SID_NAME_MAPPING_OPERATION_ADD_OUTPUT AddOutput;
CASE( LsaSidNameMappingOperation_Remove )
LSA_SID_NAME_MAPPING_OPERATION_REMOVE_OUTPUT RemoveOutput;
CASE( LsaSidNameMappingOperation_AddMultiple )
LSA_SID_NAME_MAPPING_OPERATION_ADD_MULTIPLE_OUTPUT AddMultipleOutput;
} LSA_SID_NAME_MAPPING_OPERATION_OUTPUT, *PLSA_SID_NAME_MAPPING_OPERATION_OUTPUT;
NTSTATUS
LsaLookupManageSidNameMapping(
__in LSA_SID_NAME_MAPPING_OPERATION_TYPE OperationType,
__in PLSA_SID_NAME_MAPPING_OPERATION_INPUT OperationInput,
__out PLSA_SID_NAME_MAPPING_OPERATION_OUTPUT *OperationOutput
);
#ifdef __cplusplus
}
#endif
#undef SIZE_IS
#undef SWITCH_IS
#undef SWITCH_TYPE
#undef CASE
#undef RANGE
#undef VAR_SIZE_ARRAY
#undef SID_POINTER
#undef REF
#endif // _LSALOOKUPI_

View File

@ -21,9 +21,9 @@
#ifndef _MY_VERSION_H #ifndef _MY_VERSION_H
#define _MY_VERSION_H #define _MY_VERSION_H
#define MY_VERSION_BINARY 5,56,1 #define MY_VERSION_BINARY 5,57,0
#define MY_VERSION_STRING "5.56.1" #define MY_VERSION_STRING "5.57.0"
#define MY_VERSION_COMPAT "5.55.0" // this refers to the driver ABI compatibility #define MY_VERSION_COMPAT "5.57.0" // this refers to the driver ABI compatibility
// These #defines are used by either Resource Compiler or NSIS installer // These #defines are used by either Resource Compiler or NSIS installer
#define SBIE_INSTALLER_PATH "..\\Bin\\" #define SBIE_INSTALLER_PATH "..\\Bin\\"

View File

@ -663,9 +663,10 @@ _FX BOOLEAN AdvApi_EnableDisableSRP(BOOLEAN Enable)
if (! AdvApi_Module) if (! AdvApi_Module)
return FALSE; return FALSE;
if (! __sys_SaferComputeTokenFromLevel) { if (! __sys_SaferComputeTokenFromLevel) {
HMODULE module = AdvApi_Module;
P_SaferComputeTokenFromLevel SaferComputeTokenFromLevel = P_SaferComputeTokenFromLevel SaferComputeTokenFromLevel =
(P_SaferComputeTokenFromLevel)GetProcAddress( (P_SaferComputeTokenFromLevel)GetProcAddress(
AdvApi_Module, "SaferComputeTokenFromLevel"); module, "SaferComputeTokenFromLevel");
if (SaferComputeTokenFromLevel) { if (SaferComputeTokenFromLevel) {
SBIEDLL_HOOK(AdvApi_,SaferComputeTokenFromLevel); SBIEDLL_HOOK(AdvApi_,SaferComputeTokenFromLevel);
} }
@ -718,7 +719,7 @@ DWORD Ntmarta_GetSecurityInfo(
#define SBIEDLL_HOOK2(pfx,proc) \ #define SBIEDLL_HOOK2(pfx,proc) \
*(ULONG_PTR *)&__sys_##pfx##proc = (ULONG_PTR) \ *(ULONG_PTR *)&__sys_##pfx##proc = (ULONG_PTR) \
SbieDll_Hook(#proc, proc, pfx##proc); \ SbieDll_Hook(#proc, proc, pfx##proc, module); \
if (! __sys_##pfx##proc) return FALSE; if (! __sys_##pfx##proc) return FALSE;
_FX BOOLEAN Ntmarta_Init(HMODULE module) _FX BOOLEAN Ntmarta_Init(HMODULE module)

View File

@ -93,7 +93,7 @@ static HRESULT Com_CoCreateInstanceEx(
REFCLSID rclsid, void *pUnkOuter, ULONG clsctx, void *pServerInfo, REFCLSID rclsid, void *pUnkOuter, ULONG clsctx, void *pServerInfo,
ULONG cmq, MULTI_QI *pmqs); ULONG cmq, MULTI_QI *pmqs);
static BOOLEAN Com_Hook_CoUnmarshalInterface_W8(UCHAR *code); static BOOLEAN Com_Hook_CoUnmarshalInterface_W8(UCHAR *code, HMODULE module);
static HRESULT __fastcall Com_CoUnmarshalInterface_W8( static HRESULT __fastcall Com_CoUnmarshalInterface_W8(
ULONG_PTR StreamAddr, ULONG64 zero, REFIID riid, void **ppv); ULONG_PTR StreamAddr, ULONG64 zero, REFIID riid, void **ppv);
@ -866,7 +866,7 @@ _FX HRESULT Com_CoCreateInstanceEx(
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Com_Hook_CoUnmarshalInterface_W8(UCHAR *code) _FX BOOLEAN Com_Hook_CoUnmarshalInterface_W8(UCHAR *code, HMODULE module)
{ {
// //
@ -1399,7 +1399,7 @@ _FX BOOLEAN Com_Init_ComBase(HMODULE module)
if (!Ipc_OpenCOM) { if (!Ipc_OpenCOM) {
if (Dll_OsBuild >= 8400) { if (Dll_OsBuild >= 8400) {
if (!Com_Hook_CoUnmarshalInterface_W8( if (!Com_Hook_CoUnmarshalInterface_W8(
(UCHAR*)CoUnmarshalInterface)) (UCHAR*)CoUnmarshalInterface, module))
return FALSE; return FALSE;
} }
else { else {

View File

@ -160,7 +160,7 @@ extern const WCHAR *Pst_OpenProtectedStorage;
*(ULONG_PTR *)&__sys_##proc = (ULONG_PTR)Ldr_GetProcAddrNew(DllName_advapi32, L#proc, #proc); \ *(ULONG_PTR *)&__sys_##proc = (ULONG_PTR)Ldr_GetProcAddrNew(DllName_advapi32, L#proc, #proc); \
if (*(ULONG_PTR *)&__sys_##proc) { \ if (*(ULONG_PTR *)&__sys_##proc) { \
*(ULONG_PTR *)&__sys_##proc = (ULONG_PTR) \ *(ULONG_PTR *)&__sys_##proc = (ULONG_PTR) \
SbieDll_Hook(#proc, __sys_##proc, Cred_##proc); \ SbieDll_Hook(#proc, __sys_##proc, Cred_##proc, module); \
if (! __sys_##proc) return FALSE; \ if (! __sys_##proc) return FALSE; \
} }

View File

@ -464,6 +464,7 @@ int Crypt_GetKeyStorageInterface(void * a, void *data, void *c)
ClassPtr = (KeyInterfaceClass*)(*(ULONG_PTR *)data); ClassPtr = (KeyInterfaceClass*)(*(ULONG_PTR *)data);
if (__sys_CryptClassErrorHandler != ClassPtr->ErrorHandler) { if (__sys_CryptClassErrorHandler != ClassPtr->ErrorHandler) {
HMODULE module = NULL; // fix-me:
CryptClassErrorHandler = (P_CryptClassErrorHandler)ClassPtr->ErrorHandler; CryptClassErrorHandler = (P_CryptClassErrorHandler)ClassPtr->ErrorHandler;
SBIEDLL_HOOK(Crypt_, CryptClassErrorHandler); SBIEDLL_HOOK(Crypt_, CryptClassErrorHandler);
} }

View File

@ -119,6 +119,8 @@ __declspec(dllimport) NTSTATUS LdrGetDllHandle(
_FX int Debug_Init(void) _FX int Debug_Init(void)
{ {
HMODULE module = NULL; // fix-me
P_OutputDebugString OutputDebugStringW; P_OutputDebugString OutputDebugStringW;
P_OutputDebugString OutputDebugStringA; P_OutputDebugString OutputDebugStringA;
P_RtlSetLastWin32Error RtlSetLastWin32Error; P_RtlSetLastWin32Error RtlSetLastWin32Error;

View File

@ -569,7 +569,7 @@ void Gui_AllowSetForegroundWindow(void);
void Gdi_SplWow64(BOOLEAN Register); void Gdi_SplWow64(BOOLEAN Register);
BOOLEAN Gdi_InitZero(void); BOOLEAN Gdi_InitZero(HMODULE module);
void Gui_ResetClipCursor(void); void Gui_ResetClipCursor(void);

View File

@ -49,26 +49,59 @@ BOOLEAN SbieDll_FuncSkipHook(const char* func);
#ifdef _WIN64 #ifdef _WIN64
typedef struct _VECTOR_TABLE { typedef struct _VECTOR_TABLE {
LIST_ELEM list_elem;
void * offset; void * offset;
int index; int index;
int maxEntries; int maxEntries;
} VECTOR_TABLE; } VECTOR_TABLE;
BOOL bVTableEable = TRUE; //BOOL bVTableEable = TRUE;
#define NUM_VTABLES 0x10 //#define NUM_VTABLES 0x10
#define VTABLE_SIZE 0x4000 //16k enough for 2048 8 byte entries #define VTABLE_SIZE 0x4000 //16k enough for 2048 8 byte entrys
VECTOR_TABLE SbieDllVectorTable[NUM_VTABLES] = { //VECTOR_TABLE SbieDllVectorTable[NUM_VTABLES] = {
{0,0,0},{0,0,0},{0,0,0},{0,0,0}, // {0,0,0},{0,0,0},{0,0,0},{0,0,0},
{0,0,0},{0,0,0},{0,0,0},{0,0,0}, // {0,0,0},{0,0,0},{0,0,0},{0,0,0},
{0,0,0},{0,0,0},{0,0,0},{0,0,0}, // {0,0,0},{0,0,0},{0,0,0},{0,0,0},
{0,0,0},{0,0,0},{0,0,0},{0,0,0} // {0,0,0},{0,0,0},{0,0,0},{0,0,0}
}; //};
extern CRITICAL_SECTION VT_CriticalSection; //CRITICAL_SECTION VT_CriticalSection;
#endif _WIN64 #endif _WIN64
extern ULONG Dll_Windows; extern ULONG Dll_Windows;
typedef struct _MODULE_HOOK {
LIST_ELEM list_elem;
HMODULE module;
POOL* pool;
#ifdef _WIN64
LIST vTables;
#endif
} MODULE_HOOK;
LIST Dll_ModuleHooks;
CRITICAL_SECTION Dll_ModuleHooks_CritSec;
//---------------------------------------------------------------------------
// SbieApi_HookInit
//---------------------------------------------------------------------------
_FX void SbieDll_HookInit()
{
//#ifdef _WIN64
// InitializeCriticalSection(&VT_CriticalSection);
//#endif
InitializeCriticalSection(&Dll_ModuleHooks_CritSec);
List_Init(&Dll_ModuleHooks);
}
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// SbieApi_HookTramp // SbieApi_HookTramp
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@ -98,11 +131,11 @@ _FX LONG SbieApi_HookTramp(void *Source, void *Trampoline)
_FX void *SbieDll_Hook( _FX void *SbieDll_Hook(
const char *SourceFuncName, void *SourceFunc, void *DetourFunc) const char *SourceFuncName, void *SourceFunc, void *DetourFunc, HMODULE module)
{ {
static const WCHAR *_fmt1 = L"%s (%d)"; static const WCHAR *_fmt1 = L"%s (%d)";
static const WCHAR *_fmt2 = L"%s (%d, %d)"; static const WCHAR *_fmt2 = L"%s (%d, %d)";
UCHAR *tramp, *func; UCHAR *tramp, *func = NULL;
void* RegionBase; void* RegionBase;
SIZE_T RegionSize; SIZE_T RegionSize;
ULONG prot, dummy_prot; ULONG prot, dummy_prot;
@ -254,6 +287,45 @@ skip_e9_rewrite: ;
#endif _WIN64 #endif _WIN64
//
// Get the module hook resource for this module, if module is NULL
// its NTDLL or a special case
//
EnterCriticalSection(&Dll_ModuleHooks_CritSec);
MODULE_HOOK* mod_hook = List_Head(&Dll_ModuleHooks);
while (mod_hook) {
if (mod_hook->module == module)
break;
mod_hook = List_Next(mod_hook);
}
if (!mod_hook) {
mod_hook = Dll_Alloc(sizeof(MODULE_HOOK));
if (!mod_hook) {
SbieApi_Log(2303, _fmt1, SourceFuncName, 51);
goto finish;
}
mod_hook->module = module;
mod_hook->pool = NULL;
#ifdef _WIN64
List_Init(&mod_hook->vTables);
#endif
List_Insert_Before(&Dll_ModuleHooks, NULL, mod_hook); // insert first as we probably will use it often in the next few calls
}
if (!mod_hook->pool) {
mod_hook->pool = Pool_CreateTagged(tzuk | 0xFF);
if (!mod_hook->pool) {
SbieApi_Log(2303, _fmt1, SourceFuncName, 52);
goto finish;
}
}
// //
// 64-bit only: if the function begins with 'call qword ptr [x]' // 64-bit only: if the function begins with 'call qword ptr [x]'
// (6 bytes) then overwrite at the call target address. // (6 bytes) then overwrite at the call target address.
@ -268,7 +340,12 @@ skip_e9_rewrite: ;
// to remove this qword before calling our detour function // to remove this qword before calling our detour function
// //
UCHAR *NewDetour = Dll_AllocCode128(); //UCHAR *NewDetour = Dll_AllocCode128();
UCHAR *NewDetour = Pool_Alloc(mod_hook->pool, 128);
if (! NewDetour) {
SbieApi_Log(2305, NULL);
goto finish;
}
NewDetour[0] = 0x58; // pop rax NewDetour[0] = 0x58; // pop rax
NewDetour[1] = 0x48; // mov rax, DetourFunc NewDetour[1] = 0x48; // mov rax, DetourFunc
@ -309,14 +386,19 @@ skip_e9_rewrite: ;
#endif _WIN64 #endif _WIN64
// //
// invoke the driver to create a trampoline // create the trampoline
// //
tramp = Dll_AllocCode128(); //tramp = Dll_AllocCode128();
tramp = Pool_Alloc(mod_hook->pool, 128);
if (! tramp) {
SbieApi_Log(2305, NULL);
goto finish;
}
if (SbieApi_HookTramp(SourceFunc, tramp) != 0) { if (SbieApi_HookTramp(SourceFunc, tramp) != 0) {
SbieApi_Log(2303, _fmt1, SourceFuncName, 2); SbieApi_Log(2303, _fmt1, SourceFuncName, 2);
return NULL; goto finish;
} }
//ULONG ByteCount = *(ULONG*)(tramp + 80); //ULONG ByteCount = *(ULONG*)(tramp + 80);
@ -346,7 +428,8 @@ skip_e9_rewrite: ;
if (!VirtualProtect(RegionBase, RegionSize, PAGE_EXECUTE_READWRITE, &prot)) { if (!VirtualProtect(RegionBase, RegionSize, PAGE_EXECUTE_READWRITE, &prot)) {
ULONG err = GetLastError(); ULONG err = GetLastError();
SbieApi_Log(2303, _fmt2, SourceFuncName, 33, err); SbieApi_Log(2303, _fmt2, SourceFuncName, 33, err);
return NULL; func = NULL;
goto finish;
} }
} }
@ -389,15 +472,17 @@ skip_e9_rewrite: ;
BOOLEAN hookset = FALSE; BOOLEAN hookset = FALSE;
BOOLEAN defaultRange = FALSE; BOOLEAN defaultRange = FALSE;
int i; //int i;
EnterCriticalSection(&VT_CriticalSection); //EnterCriticalSection(&VT_CriticalSection);
if (bVTableEable) { //if (bVTableEable) {
VECTOR_TABLE *ptrVTable = SbieDllVectorTable; //VECTOR_TABLE *ptrVTable = SbieDllVectorTable;
//default step size //default step size
//for (i = 0; i < NUM_VTABLES && !hookset; i++, ptrVTable++) {
for (i = 0; i < NUM_VTABLES && !hookset; i++, ptrVTable++) { VECTOR_TABLE* ptrVTable = List_Head(&mod_hook->vTables);
if (!ptrVTable->offset) { // if the vtable is not yet initialized initialize it do {
//if (!ptrVTable->offset) { // if the vtable is not yet initialized initialize it
if (!ptrVTable || !ptrVTable->offset) { // if there is no vtable create it
ULONG_PTR tempAddr; ULONG_PTR tempAddr;
ULONG_PTR step = 0x20000;// + VTABLE_SIZE; ULONG_PTR step = 0x20000;// + VTABLE_SIZE;
ULONG_PTR max_attempts = 0x4000000 / step; ULONG_PTR max_attempts = 0x4000000 / step;
@ -425,16 +510,31 @@ skip_e9_rewrite: ;
tempAddr -= 0x20000000; tempAddr -= 0x20000000;
} }
if (!ptrVTable) {
ptrVTable = Pool_Alloc(mod_hook->pool, sizeof(VECTOR_TABLE));
if (!ptrVTable) {
SbieApi_Log(2303, _fmt1, SourceFuncName, 53);
goto finish;
}
memset(ptrVTable, 0, sizeof(VECTOR_TABLE));
List_Insert_After(&mod_hook->vTables, NULL, ptrVTable);
}
for (; !ptrVTable->offset && max_attempts; tempAddr -= step, max_attempts--) { for (; !ptrVTable->offset && max_attempts; tempAddr -= step, max_attempts--) {
ptrVTable->offset = VirtualAlloc((void *)tempAddr, VTABLE_SIZE, MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN, PAGE_READWRITE); ptrVTable->offset = VirtualAlloc((void*)tempAddr, VTABLE_SIZE, MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN, PAGE_READWRITE);
// sprintf(buffer,"VTable Offset: func = %p, offset = %p, tryAddress = %p, attempt = 0x%x\n",func,ptrVTable->offset,tempAddr,max_attempts); // sprintf(buffer,"VTable Offset: func = %p, offset = %p, tryAddress = %p, attempt = 0x%x\n",func,ptrVTable->offset,tempAddr,max_attempts);
// OutputDebugStringA(buffer); // OutputDebugStringA(buffer);
} }
ptrVTable->index = 0; ptrVTable->index = 0;
ptrVTable->maxEntries = VTABLE_SIZE / sizeof(void *); ptrVTable->maxEntries = VTABLE_SIZE / sizeof(void*);
} }
if (ptrVTable->offset) { // check if we have an nitialized vtable
//if (ptrVTable->offset) { // check if we have an initialized vtable
if (ptrVTable && ptrVTable->offset) { // check if we have a vtable
target = (ULONG_PTR)&func[6]; target = (ULONG_PTR)&func[6];
diff = (ULONG_PTR) &((ULONG_PTR *)ptrVTable->offset)[ptrVTable->index]; diff = (ULONG_PTR) &((ULONG_PTR *)ptrVTable->offset)[ptrVTable->index];
diff = diff - target; diff = diff - target;
@ -452,19 +552,25 @@ skip_e9_rewrite: ;
} }
} }
else { // fail and disable vtable if it could not be initialized else { // fail and disable vtable if it could not be initialized
bVTableEable = FALSE; //bVTableEable = FALSE;
SbieApi_Log(2303, _fmt1, SourceFuncName, 888); SbieApi_Log(2303, _fmt1, SourceFuncName, 888);
LeaveCriticalSection(&VT_CriticalSection); //LeaveCriticalSection(&VT_CriticalSection);
return NULL; func = NULL;
goto finish;
} }
}
}
LeaveCriticalSection(&VT_CriticalSection); ptrVTable = List_Next(ptrVTable);
} while (!hookset);
//}
//}
//LeaveCriticalSection(&VT_CriticalSection);
if (!hookset) { if (!hookset) {
// OutputDebugStringA("Memory alloc failed: 12 Byte Patch Disabled\n"); // OutputDebugStringA("Memory alloc failed: 12 Byte Patch Disabled\n");
SbieApi_Log(2303, _fmt1, SourceFuncName, 999); SbieApi_Log(2303, _fmt1, SourceFuncName, 999);
return NULL; func = NULL;
goto finish;
} }
} }
@ -501,10 +607,53 @@ skip_e9_rewrite: ;
#endif _WIN64 #endif _WIN64
finish:
LeaveCriticalSection(&Dll_ModuleHooks_CritSec);
return func; return func;
} }
//---------------------------------------------------------------------------
// SbieDll_UnHookModule
//---------------------------------------------------------------------------
_FX void SbieDll_UnHookModule(HMODULE module)
{
EnterCriticalSection(&Dll_ModuleHooks_CritSec);
MODULE_HOOK* mod_hook = List_Head(&Dll_ModuleHooks);
while (mod_hook) {
if (mod_hook->module == module) {
List_Remove(&Dll_ModuleHooks, mod_hook);
#ifdef _WIN64
VECTOR_TABLE* ptrVTable = List_Head(&mod_hook->vTables);
while (ptrVTable) {
if (ptrVTable->offset)
VirtualFree(ptrVTable->offset, 0, MEM_RELEASE);
ptrVTable = List_Next(ptrVTable);
}
#endif
Pool_Delete(mod_hook->pool);
Dll_Free(mod_hook);
break;
}
mod_hook = List_Next(mod_hook);
}
LeaveCriticalSection(&Dll_ModuleHooks_CritSec);
}
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// SbieDll_Hook_CheckChromeHook // SbieDll_Hook_CheckChromeHook
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------

View File

@ -94,10 +94,6 @@ ULONG Dll_ImageType = DLL_IMAGE_UNSPECIFIED;
ULONG Dll_OsBuild = 0; // initialized by Key module ULONG Dll_OsBuild = 0; // initialized by Key module
ULONG Dll_Windows = 0; ULONG Dll_Windows = 0;
#ifdef _WIN64
CRITICAL_SECTION VT_CriticalSection;
#endif
const UCHAR *SbieDll_Version = MY_VERSION_COMPAT; const UCHAR *SbieDll_Version = MY_VERSION_COMPAT;
BOOLEAN Dll_SbieTrace = FALSE; BOOLEAN Dll_SbieTrace = FALSE;
@ -155,7 +151,6 @@ _FX BOOL WINAPI DllMain(
} else if (dwReason == DLL_PROCESS_ATTACH) { } else if (dwReason == DLL_PROCESS_ATTACH) {
#ifdef _WIN64 #ifdef _WIN64
InitializeCriticalSection(&VT_CriticalSection);
Dll_DigitalGuardian = GetModuleHandleA("DgApi64.dll"); Dll_DigitalGuardian = GetModuleHandleA("DgApi64.dll");
#else #else
Dll_DigitalGuardian = GetModuleHandleA("DgApi.dll"); Dll_DigitalGuardian = GetModuleHandleA("DgApi.dll");
@ -167,6 +162,7 @@ _FX BOOL WINAPI DllMain(
Dll_Windows = 8; Dll_Windows = 8;
} }
Dll_InitGeneric(hInstance); Dll_InitGeneric(hInstance);
SbieDll_HookInit();
} else if (dwReason == DLL_PROCESS_DETACH) { } else if (dwReason == DLL_PROCESS_DETACH) {
@ -176,11 +172,6 @@ _FX BOOL WINAPI DllMain(
Gui_ResetClipCursor(); Gui_ResetClipCursor();
} }
//#ifdef _WIN64
// // cleanup CS
// DeleteCriticalSection(&VT_CriticalSection);
//#endif
} }
return TRUE; return TRUE;

View File

@ -204,6 +204,8 @@ ALIGNED LPTOP_LEVEL_EXCEPTION_FILTER Dump_SetUnhandledExceptionFilter(
_FX int Dump_Init(void) _FX int Dump_Init(void)
{ {
HMODULE module = NULL; // fix-me
if (Dump_DbgHelpMod != NULL) if (Dump_DbgHelpMod != NULL)
return 2; return 2;

View File

@ -127,6 +127,8 @@ static const WCHAR *File_DeviceMap_EnvVar = ENV_VAR_PFX L"DEVICE_MAP";
_FX BOOLEAN File_Init(void) _FX BOOLEAN File_Init(void)
{ {
HMODULE module = NULL;
void *RtlGetFullPathName_UEx; void *RtlGetFullPathName_UEx;
void *GetTempPathW; void *GetTempPathW;
void *NtQueryDirectoryFileEx = NULL; void *NtQueryDirectoryFileEx = NULL;

View File

@ -720,7 +720,7 @@ _FX int Gdi_EnumFontFamiliesExW(
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gdi_InitZero(void) _FX BOOLEAN Gdi_InitZero(HMODULE module)
{ {
static void *Saved_GdiDllInitialize = NULL; static void *Saved_GdiDllInitialize = NULL;
void *GdiDllInitialize; void *GdiDllInitialize;
@ -784,7 +784,7 @@ _FX BOOLEAN Gdi_Full_Init_impl(HMODULE module, BOOLEAN full)
InitializeCriticalSection(&Gdi_CritSec); InitializeCriticalSection(&Gdi_CritSec);
if (!Gdi_InitZero()) if (!Gdi_InitZero(module))
return FALSE; return FALSE;
// //

View File

@ -213,9 +213,9 @@ BOOLEAN Gui_UseProxyService = TRUE;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
static BOOLEAN Gui_Init2(void); static BOOLEAN Gui_Init2(HMODULE module);
static BOOLEAN Gui_Init3(void); static BOOLEAN Gui_Init3(HMODULE module);
static BOOL Gui_SetThreadDesktop(HDESK hDesktop); static BOOL Gui_SetThreadDesktop(HDESK hDesktop);
@ -360,7 +360,7 @@ _FX BOOLEAN Gui_Init(HMODULE module)
const UCHAR *ProcName; const UCHAR *ProcName;
if (! Gdi_InitZero()) // only if Gdi_Init was not called yet if (! Gdi_InitZero(module)) // only if Gdi_Init was not called yet
return FALSE; return FALSE;
// NoSbieDesk BEGIN // NoSbieDesk BEGIN
@ -530,33 +530,33 @@ import_fail:
ok = TRUE; ok = TRUE;
if (ok) if (ok)
ok = Gui_InitClass(); ok = Gui_InitClass(module);
if (ok) if (ok)
ok = Gui_InitTitle(); ok = Gui_InitTitle(module);
if (ok) if (ok)
ok = Gui_Init2(); ok = Gui_Init2(module);
if (ok) if (ok)
ok = Gui_InitEnum(); ok = Gui_InitEnum(module);
if (ok) if (ok)
ok = Gui_InitProp(); ok = Gui_InitProp(module);
if (ok) if (ok)
ok = Gui_InitMsg(); ok = Gui_InitMsg(module);
if (ok) if (ok)
ok = Gui_InitDlgTmpl(); ok = Gui_InitDlgTmpl(module);
if (ok) if (ok)
ok = Gui_Init3(); ok = Gui_Init3(module);
if (Gui_UseProxyService) { if (Gui_UseProxyService) {
if (ok) if (ok)
ok = Gui_InitWinHooks(); ok = Gui_InitWinHooks(module);
SBIEDLL_HOOK_GUI(AttachThreadInput); SBIEDLL_HOOK_GUI(AttachThreadInput);
} }
@ -570,7 +570,7 @@ import_fail:
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_Init2(void) _FX BOOLEAN Gui_Init2(HMODULE module)
{ {
SBIEDLL_HOOK_GUI(ExitWindowsEx); SBIEDLL_HOOK_GUI(ExitWindowsEx);
SBIEDLL_HOOK_GUI(EndTask); SBIEDLL_HOOK_GUI(EndTask);
@ -633,10 +633,10 @@ _FX BOOLEAN Gui_Init2(void)
SBIEDLL_HOOK_GUI(ActivateKeyboardLayout); SBIEDLL_HOOK_GUI(ActivateKeyboardLayout);
} }
if (! Gui_InitMisc()) if (! Gui_InitMisc(module))
return FALSE; return FALSE;
if (! Gui_DDE_Init()) if (! Gui_DDE_Init(module))
return FALSE; return FALSE;
return TRUE; return TRUE;
@ -648,7 +648,7 @@ _FX BOOLEAN Gui_Init2(void)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_Init3(void) _FX BOOLEAN Gui_Init3(HMODULE module)
{ {
// //
// expect that both RegisterDeviceNotificationA and // expect that both RegisterDeviceNotificationA and
@ -754,7 +754,7 @@ _FX void Gui_InitWindows7(void)
} }
*pSourceFunc = (ULONG_PTR)SbieDll_Hook( *pSourceFunc = (ULONG_PTR)SbieDll_Hook(
FuncName, (void *)(*pSourceFunc), DetourFunc); FuncName, (void *)(*pSourceFunc), DetourFunc, NULL); // fix-me: module
} }
} }
} }
@ -2651,11 +2651,11 @@ _FX NTSTATUS ComDlg32_GetOpenFileNameW(LPVOID lpofn)
return bRet; return bRet;
} }
_FX BOOLEAN ComDlg32_Init(HMODULE hModule) _FX BOOLEAN ComDlg32_Init(HMODULE module)
{ {
//if (_wcsicmp(Dll_ImageName, L"opera.exe") == 0) //if (_wcsicmp(Dll_ImageName, L"opera.exe") == 0)
//{ //{
void *GetOpenFileNameW = GetProcAddress(hModule, "GetOpenFileNameW"); void *GetOpenFileNameW = GetProcAddress(module, "GetOpenFileNameW");
SBIEDLL_HOOK(ComDlg32_, GetOpenFileNameW); SBIEDLL_HOOK(ComDlg32_, GetOpenFileNameW);
//} //}

View File

@ -740,7 +740,7 @@ extern P_LoadString __sys_LoadStringW;
#define SBIEDLL_HOOK_GUI(proc) \ #define SBIEDLL_HOOK_GUI(proc) \
*(ULONG_PTR *)&__sys_##proc = (ULONG_PTR) \ *(ULONG_PTR *)&__sys_##proc = (ULONG_PTR) \
SbieDll_Hook(#proc, __sys_##proc, Gui_##proc); \ SbieDll_Hook(#proc, __sys_##proc, Gui_##proc, module); \
if (! __sys_##proc) return FALSE; if (! __sys_##proc) return FALSE;
@ -764,7 +764,7 @@ LRESULT Gui_WindowProcA(
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Gui_InitClass(void); BOOLEAN Gui_InitClass(HMODULE module);
void Gui_Hook_CREATESTRUCT_Handler(void); void Gui_Hook_CREATESTRUCT_Handler(void);
@ -784,7 +784,7 @@ void Gui_CREATESTRUCT_Restore(LPARAM lParam);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Gui_InitTitle(void); BOOLEAN Gui_InitTitle(HMODULE module);
BOOLEAN Gui_ShouldCreateTitle(HWND hWnd); BOOLEAN Gui_ShouldCreateTitle(HWND hWnd);
@ -800,13 +800,13 @@ int Gui_FixTitleA(HWND hWnd, UCHAR *lpWindowTitle, int len);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Gui_InitEnum(void); BOOLEAN Gui_InitEnum(HMODULE module);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Gui_InitProp(void); BOOLEAN Gui_InitProp(HMODULE module);
void Gui_SetWindowProc(HWND hWnd, BOOLEAN force); void Gui_SetWindowProc(HWND hWnd, BOOLEAN force);
@ -814,13 +814,13 @@ void Gui_SetWindowProc(HWND hWnd, BOOLEAN force);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Gui_InitMsg(void); BOOLEAN Gui_InitMsg(HMODULE module);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Gui_InitWinHooks(void); BOOLEAN Gui_InitWinHooks(HMODULE module);
LRESULT Gui_RegisterWinHook(DWORD dwThreadId, ULONG64 ghk); LRESULT Gui_RegisterWinHook(DWORD dwThreadId, ULONG64 ghk);
@ -830,7 +830,7 @@ LRESULT Gui_NotifyWinHooks(void);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Gui_InitDlgTmpl(void); BOOLEAN Gui_InitDlgTmpl(HMODULE module);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@ -842,7 +842,7 @@ BOOLEAN Ole_DoDragDrop(HWND hWnd, WPARAM wParam, LPARAM lParam);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Gui_InitMisc(void); BOOLEAN Gui_InitMisc(HMODULE module);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@ -859,7 +859,7 @@ void *Gui_CallProxyEx(
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Gui_DDE_Init(void); BOOLEAN Gui_DDE_Init(HMODULE module);
WPARAM Gui_DDE_INITIATE_Received(HWND hWnd, WPARAM wParam); WPARAM Gui_DDE_INITIATE_Received(HWND hWnd, WPARAM wParam);

View File

@ -122,7 +122,7 @@ BOOLEAN Gui_OpenAllWinClasses = FALSE;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_InitClass(void) _FX BOOLEAN Gui_InitClass(HMODULE module)
{ {
static const WCHAR *Sandbox = L"Sandbox"; static const WCHAR *Sandbox = L"Sandbox";
ULONG len; ULONG len;

View File

@ -79,6 +79,8 @@ static P_GetMessage __sys_GetMessageW = NULL;
_FX BOOLEAN Gui_InitConsole1(void) _FX BOOLEAN Gui_InitConsole1(void)
{ {
HMODULE module = NULL; // fix-me
// NoSbieCons BEGIN // NoSbieCons BEGIN
if (Dll_CompartmentMode || SbieApi_QueryConfBool(NULL, L"NoSandboxieConsole", FALSE)) { if (Dll_CompartmentMode || SbieApi_QueryConfBool(NULL, L"NoSandboxieConsole", FALSE)) {

View File

@ -160,7 +160,7 @@ static ULONG Gui_DDE_REQ_Len;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_DDE_Init(void) _FX BOOLEAN Gui_DDE_Init(HMODULE module)
{ {
__sys_PackDDElParam = __sys_PackDDElParam =
Ldr_GetProcAddrNew(DllName_user32, L"PackDDElParam","PackDDElParam"); Ldr_GetProcAddrNew(DllName_user32, L"PackDDElParam","PackDDElParam");

View File

@ -127,7 +127,7 @@ static LRESULT Gui_MyDialogProc2(
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_InitDlgTmpl(void) _FX BOOLEAN Gui_InitDlgTmpl(HMODULE module)
{ {
if (! Gui_RenameClasses) if (! Gui_RenameClasses)
return TRUE; return TRUE;

View File

@ -44,7 +44,7 @@ typedef struct _GUI_ENUM_PROC_PARM {
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
static BOOLEAN Gui_HookQueryWindow(void); static BOOLEAN Gui_HookQueryWindow(HMODULE module);
static ULONG_PTR Gui_NtUserQueryWindow(HWND hWnd, ULONG_PTR type); static ULONG_PTR Gui_NtUserQueryWindow(HWND hWnd, ULONG_PTR type);
@ -182,7 +182,7 @@ static BOOLEAN Winsta_Hack = FALSE;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_InitEnum(void) _FX BOOLEAN Gui_InitEnum(HMODULE module)
{ {
// //
// hook EnumWindow* and FindWindow* family of functions // hook EnumWindow* and FindWindow* family of functions
@ -190,7 +190,7 @@ _FX BOOLEAN Gui_InitEnum(void)
if (! Gui_OpenAllWinClasses) { if (! Gui_OpenAllWinClasses) {
if (Gui_UseProxyService && !Gui_HookQueryWindow()) if (Gui_UseProxyService && !Gui_HookQueryWindow(module))
return FALSE; return FALSE;
if (Gui_UseProxyService && !Dll_SkipHook(L"enumwin")) { if (Gui_UseProxyService && !Dll_SkipHook(L"enumwin")) {
@ -260,7 +260,7 @@ _FX BOOLEAN Gui_InitEnum(void)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_HookQueryWindow(void) _FX BOOLEAN Gui_HookQueryWindow(HMODULE module)
{ {
static const WCHAR *_ProcName = L"IsHungAppWindow"; static const WCHAR *_ProcName = L"IsHungAppWindow";
static char *_ProcNameA = "IsHungAppWindow"; static char *_ProcNameA = "IsHungAppWindow";

View File

@ -103,7 +103,7 @@ static BOOLEAN Gui_HookInit = FALSE;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_InitWinHooks(void) _FX BOOLEAN Gui_InitWinHooks(HMODULE module)
{ {
InitializeCriticalSection(&Gui_HooksCritSec); InitializeCriticalSection(&Gui_HooksCritSec);
List_Init(&Gui_Hooks); List_Init(&Gui_Hooks);

View File

@ -153,7 +153,7 @@ static HANDLE Gui_DummyInputDesktopHandle = NULL;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_InitMisc(void) _FX BOOLEAN Gui_InitMisc(HMODULE module)
{ {
if (! Gui_OpenAllWinClasses) { if (! Gui_OpenAllWinClasses) {

View File

@ -132,7 +132,7 @@ static LRESULT Gui_SendMessageA_MdiCreate(HWND hWnd, LPARAM lParam);
static LRESULT Gui_DispatchMessage8(const MSG *lpmsg, ULONG IsAscii); static LRESULT Gui_DispatchMessage8(const MSG *lpmsg, ULONG IsAscii);
static BOOLEAN Gui_Hook_DispatchMessage8(void); static BOOLEAN Gui_Hook_DispatchMessage8(HMODULE module);
static P_DispatchMessage8 __sys_DispatchMessage8 = 0; static P_DispatchMessage8 __sys_DispatchMessage8 = 0;
@ -160,7 +160,7 @@ BOOLEAN Gui_DispatchMessageCalled = FALSE;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_InitMsg(void) _FX BOOLEAN Gui_InitMsg(HMODULE module)
{ {
// //
// hook SendMessage and PostMessage family of functions // hook SendMessage and PostMessage family of functions
@ -211,7 +211,7 @@ _FX BOOLEAN Gui_InitMsg(void)
SBIEDLL_HOOK_GUI(DispatchMessageA); SBIEDLL_HOOK_GUI(DispatchMessageA);
SBIEDLL_HOOK_GUI(DispatchMessageW); SBIEDLL_HOOK_GUI(DispatchMessageW);
} else if (! Gui_Hook_DispatchMessage8()) } else if (! Gui_Hook_DispatchMessage8(module))
return FALSE; return FALSE;
#endif _WIN64 #endif _WIN64
@ -852,7 +852,7 @@ _FX LRESULT Gui_DispatchMessage8(const MSG *lpmsg, ULONG IsAscii)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_Hook_DispatchMessage8(void) _FX BOOLEAN Gui_Hook_DispatchMessage8(HMODULE module)
{ {
// //
// on Windows 8, the DispatchMessageA and DispatchMessageW functions // on Windows 8, the DispatchMessageA and DispatchMessageW functions

View File

@ -72,7 +72,7 @@ static ULONG Gui_SetWindowLongA(HWND hWnd, int nIndex, ULONG dwNew);
static ULONG_PTR Gui_SetWindowLong8( static ULONG_PTR Gui_SetWindowLong8(
HWND hWnd, int nIndex, ULONG_PTR dwNew, ULONG IsAscii); HWND hWnd, int nIndex, ULONG_PTR dwNew, ULONG IsAscii);
static BOOLEAN Gui_Hook_SetWindowLong8(void); static BOOLEAN Gui_Hook_SetWindowLong8(HMODULE module);
static ULONG Gui_GetClassLongW(HWND hWnd, int nIndex); static ULONG Gui_GetClassLongW(HWND hWnd, int nIndex);
@ -93,7 +93,7 @@ static ULONG_PTR Gui_SetWindowLongPtrA(
static ULONG_PTR Gui_SetWindowLongPtr8( static ULONG_PTR Gui_SetWindowLongPtr8(
HWND hWnd, int nIndex, ULONG_PTR dwNew, ULONG IsAscii); HWND hWnd, int nIndex, ULONG_PTR dwNew, ULONG IsAscii);
static BOOLEAN Gui_Hook_SetWindowLongPtr8(void); static BOOLEAN Gui_Hook_SetWindowLongPtr8(HMODULE module);
static ULONG_PTR Gui_GetClassLongPtrW(HWND hWnd, int nIndex); static ULONG_PTR Gui_GetClassLongPtrW(HWND hWnd, int nIndex);
@ -134,7 +134,7 @@ static P_SetWindowLongPtr8 __sys_SetWindowLongPtr8 = 0;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_InitProp(void) _FX BOOLEAN Gui_InitProp(HMODULE module)
{ {
// //
// initialize our Drag-n-Drop atoms // initialize our Drag-n-Drop atoms
@ -180,7 +180,7 @@ _FX BOOLEAN Gui_InitProp(void)
SBIEDLL_HOOK_GUI(SetWindowLongA); SBIEDLL_HOOK_GUI(SetWindowLongA);
SBIEDLL_HOOK_GUI(SetWindowLongW); SBIEDLL_HOOK_GUI(SetWindowLongW);
} else if (! Gui_Hook_SetWindowLong8()) } else if (! Gui_Hook_SetWindowLong8(module))
return FALSE; return FALSE;
#else ! _WIN64 #else ! _WIN64
@ -204,7 +204,7 @@ _FX BOOLEAN Gui_InitProp(void)
SBIEDLL_HOOK_GUI(SetWindowLongPtrA); SBIEDLL_HOOK_GUI(SetWindowLongPtrA);
SBIEDLL_HOOK_GUI(SetWindowLongPtrW); SBIEDLL_HOOK_GUI(SetWindowLongPtrW);
} else if (! Gui_Hook_SetWindowLongPtr8()) } else if (! Gui_Hook_SetWindowLongPtr8(module))
return FALSE; return FALSE;
SBIEDLL_HOOK_GUI(GetClassLongPtrA); SBIEDLL_HOOK_GUI(GetClassLongPtrA);
@ -1053,7 +1053,7 @@ _FX ULONG_PTR Gui_SetWindowLong8(
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_Hook_SetWindowLong8(void) _FX BOOLEAN Gui_Hook_SetWindowLong8(HMODULE module)
{ {
// //
// on Windows 8.1, the SetWindowLongA and SetWindowLongW functions // on Windows 8.1, the SetWindowLongA and SetWindowLongW functions
@ -1153,7 +1153,7 @@ _FX ULONG_PTR Gui_SetWindowLongPtr8(
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_Hook_SetWindowLongPtr8(void) _FX BOOLEAN Gui_Hook_SetWindowLongPtr8(HMODULE module)
{ {
// //
// on Windows 8, the SetWindowLongPtrA and SetWindowLongPtrW functions // on Windows 8, the SetWindowLongPtrA and SetWindowLongPtrW functions

View File

@ -60,7 +60,7 @@ static ANSI_STRING Gui_BoxNameTitleA;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Gui_InitTitle(void) _FX BOOLEAN Gui_InitTitle(HMODULE module)
{ {
WCHAR buf[10]; WCHAR buf[10];

View File

@ -326,6 +326,8 @@ BOOLEAN RpcRt_IsDynamicPortOpen(const WCHAR* wszPortName);
_FX BOOLEAN Ipc_Init(void) _FX BOOLEAN Ipc_Init(void)
{ {
HMODULE module = NULL;
void *NtAlpcCreatePort; void *NtAlpcCreatePort;
void *NtAlpcConnectPort; void *NtAlpcConnectPort;
void *NtAlpcConnectPortEx; void *NtAlpcConnectPortEx;

View File

@ -353,6 +353,8 @@ BOOLEAN Key_Delete_v2 = FALSE;
_FX BOOLEAN Key_Init(void) _FX BOOLEAN Key_Init(void)
{ {
HMODULE module = NULL;
void *NtRenameKey; void *NtRenameKey;
void *NtOpenKeyEx; void *NtOpenKeyEx;

View File

@ -70,8 +70,8 @@ typedef union _LDR_DLL_NOTIFICATION_DATA {
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
static void Ldr_CallOneDllCallback(const UCHAR *ImageNameA, ULONG_PTR ImageBase); static void Ldr_CallOneDllCallback(const UCHAR *ImageNameA, ULONG_PTR ImageBase, BOOL LoadState);
static void Ldr_CallOneDllCallbackXP(const UCHAR *ImageNameA, ULONG_PTR ImageBase); static void Ldr_CallOneDllCallbackXP(const UCHAR *ImageNameA, ULONG_PTR ImageBase, BOOL LoadState);
static void Ldr_CallDllCallbacks(void); static void Ldr_CallDllCallbacks(void);
static NTSTATUS Ldr_LdrLoadDll(WCHAR *PathString, ULONG *DllFlags, UNICODE_STRING *ModuleName, HANDLE *ModuleHandle); static NTSTATUS Ldr_LdrLoadDll(WCHAR *PathString, ULONG *DllFlags, UNICODE_STRING *ModuleName, HANDLE *ModuleHandle);
@ -90,9 +90,9 @@ static NTSTATUS Ldr_LdrQueryImageFileExecutionOptions(
static ULONG_PTR Ldr_NtApphelpCacheControl( static ULONG_PTR Ldr_NtApphelpCacheControl(
ULONG_PTR Unknown1, ULONG_PTR Unknown2); ULONG_PTR Unknown1, ULONG_PTR Unknown2);
void Ldr_MyDllCallbackA(const CHAR *ImageName, HMODULE ImageBase); void Ldr_MyDllCallbackA(const CHAR *ImageName, HMODULE ImageBase, BOOL LoadState);
void Ldr_MyDllCallbackW(const WCHAR *ImageName, HMODULE ImageBase); void Ldr_MyDllCallbackW(const WCHAR *ImageName, HMODULE ImageBase, BOOL LoadState);
void Ldr_MyDllCallbackNew(const WCHAR *ImageName, HMODULE ImageBase); void Ldr_MyDllCallbackNew(const WCHAR *ImageName, HMODULE ImageBase, BOOL LoadState);
static void *Ldr_GetProcAddr_2(const WCHAR *DllName, const WCHAR *ProcName); static void *Ldr_GetProcAddr_2(const WCHAR *DllName, const WCHAR *ProcName);
@ -145,9 +145,9 @@ typedef NTSTATUS(*P_NtTerminateProcess)(HANDLE ProcessHandle, NTSTATUS ExitStatu
typedef NTSTATUS(*P_NtLoadDriver)(UNICODE_STRING *RegistryPath); typedef NTSTATUS(*P_NtLoadDriver)(UNICODE_STRING *RegistryPath);
typedef void(*P_LdrDllCallback)(const UCHAR *ImageName, HMODULE ImageBase); typedef void(*P_LdrDllCallback)(const UCHAR *ImageName, HMODULE ImageBase, BOOL LoadState);
typedef void(*P_LdrDllCallbackW)(const WCHAR *ImageName, HMODULE ImageBase); typedef void(*P_LdrDllCallbackW)(const WCHAR *ImageName, HMODULE ImageBase, BOOL LoadState);
typedef void(*P_Ldr_CallOneDllCallback)(const UCHAR *ImageNameA, ULONG_PTR ImageBase); typedef void(*P_Ldr_CallOneDllCallback)(const UCHAR *ImageNameA, ULONG_PTR ImageBase, BOOL LoadState);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@ -280,13 +280,13 @@ void CALLBACK Ldr_LdrDllNotification(ULONG NotificationReason, PLDR_DLL_NOTIFICA
if (NotificationReason == 1) { if (NotificationReason == 1) {
status = __sys_LdrLockLoaderLock(0, NULL, &LdrCookie); status = __sys_LdrLockLoaderLock(0, NULL, &LdrCookie);
Ldr_MyDllCallbackNew(NotificationData->Loaded.BaseDllName->Buffer, (HMODULE)NotificationData->Loaded.DllBase); Ldr_MyDllCallbackNew(NotificationData->Loaded.BaseDllName->Buffer, (HMODULE)NotificationData->Loaded.DllBase, TRUE);
__sys_LdrUnlockLoaderLock(0, LdrCookie); __sys_LdrUnlockLoaderLock(0, LdrCookie);
return; return;
} }
else if (NotificationReason == 2) { else if (NotificationReason == 2) {
Ldr_MyDllCallbackNew(NotificationData->Unloaded.BaseDllName->Buffer, 0); Ldr_MyDllCallbackNew(NotificationData->Unloaded.BaseDllName->Buffer, (HMODULE)NotificationData->Loaded.DllBase, FALSE);
} }
return; return;
} }
@ -382,6 +382,8 @@ BOOL LdrCheckImmersive()
_FX BOOLEAN Ldr_Init() _FX BOOLEAN Ldr_Init()
{ {
HMODULE module = NULL;
UCHAR *ReadImageFileExecOptions; UCHAR *ReadImageFileExecOptions;
// //
@ -547,7 +549,7 @@ _FX BOOLEAN SbieDll_RegisterDllCallback(void *Callback)
// Ldr_CallOneDllCallback // Ldr_CallOneDllCallback
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX void Ldr_CallOneDllCallback(const UCHAR *ImageNameA, ULONG_PTR ImageBase) _FX void Ldr_CallOneDllCallback(const UCHAR *ImageNameA, ULONG_PTR ImageBase, BOOL LoadState)
{ {
ULONG i; ULONG i;
@ -556,7 +558,7 @@ _FX void Ldr_CallOneDllCallback(const UCHAR *ImageNameA, ULONG_PTR ImageBase)
if (!callback) if (!callback)
break; break;
__try { __try {
((P_LdrDllCallback)callback)(ImageNameA, (HMODULE)ImageBase); ((P_LdrDllCallback)callback)(ImageNameA, (HMODULE)ImageBase, LoadState);
} }
__except (EXCEPTION_EXECUTE_HANDLER) { __except (EXCEPTION_EXECUTE_HANDLER) {
} }
@ -564,7 +566,7 @@ _FX void Ldr_CallOneDllCallback(const UCHAR *ImageNameA, ULONG_PTR ImageBase)
} }
_FX void Ldr_CallOneDllCallbackXP(const UCHAR *ImageNameA, ULONG_PTR ImageBase) _FX void Ldr_CallOneDllCallbackXP(const UCHAR *ImageNameA, ULONG_PTR ImageBase, BOOL LoadState)
{ {
ULONG i; ULONG i;
@ -581,7 +583,7 @@ _FX void Ldr_CallOneDllCallbackXP(const UCHAR *ImageNameA, ULONG_PTR ImageBase)
break; break;
__try { __try {
((P_LdrDllCallbackW)callback)(ImageNameW, (HMODULE)ImageBase); ((P_LdrDllCallbackW)callback)(ImageNameW, (HMODULE)ImageBase, LoadState);
} }
__except (EXCEPTION_EXECUTE_HANDLER) { __except (EXCEPTION_EXECUTE_HANDLER) {
} }
@ -678,7 +680,8 @@ _FX void Ldr_CallDllCallbacks(void)
if (!found) { if (!found) {
__my_Ldr_CallOneDllCallback(pOld->Path + pOld->NameOffset, 0); __my_Ldr_CallOneDllCallback(pOld->Path + pOld->NameOffset,
pNew->ImageBaseAddress, FALSE);
} }
} }
} }
@ -724,7 +727,7 @@ _FX void Ldr_CallDllCallbacks(void)
RtlFreeUnicodeString(&uni); RtlFreeUnicodeString(&uni);
__my_Ldr_CallOneDllCallback(pNew->Path + pNew->NameOffset, __my_Ldr_CallOneDllCallback(pNew->Path + pNew->NameOffset,
pNew->ImageBaseAddress); pNew->ImageBaseAddress, TRUE);
if (OldState) if (OldState)
Ldr_SetDdagState_W8(pNew->ImageBaseAddress, OldState); Ldr_SetDdagState_W8(pNew->ImageBaseAddress, OldState);
@ -968,50 +971,54 @@ _FX ULONG_PTR Ldr_NtApphelpCacheControl(
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX void Ldr_MyDllCallbackA(const CHAR *ImageName, HMODULE ImageBase) _FX void Ldr_MyDllCallbackA(const CHAR *ImageName, HMODULE ImageBase, BOOL LoadState)
{ {
// //
// invoke our sub-modules as necessary // invoke our sub-modules as necessary
// //
if (ImageBase) {
DLL *dll = Ldr_Dlls; DLL *dll = Ldr_Dlls;
while (dll->nameA) { while (dll->nameA) {
if (_stricmp(ImageName, dll->nameA) == 0 && (dll->state & 2) == 0) { if (_stricmp(ImageName, dll->nameA) == 0 && (dll->state & 2) == 0) {
if (LoadState) {
BOOLEAN ok = dll->init_func(ImageBase); BOOLEAN ok = dll->init_func(ImageBase);
if (!ok) if (!ok)
SbieApi_Log(2318, dll->nameW); SbieApi_Log(2318, dll->nameW);
break;
} }
++dll; else {
SbieDll_UnHookModule(ImageBase);
}
break;
} }
++dll;
} }
} }
_FX void Ldr_MyDllCallbackW(const WCHAR *ImageName, HMODULE ImageBase) _FX void Ldr_MyDllCallbackW(const WCHAR *ImageName, HMODULE ImageBase, BOOL LoadState)
{ {
// //
// invoke our sub-modules as necessary // invoke our sub-modules as necessary
// //
if (ImageBase) {
DLL *dll = Ldr_Dlls; DLL *dll = Ldr_Dlls;
while (dll->nameW) { while (dll->nameW) {
if (_wcsicmp(ImageName, dll->nameW) == 0 && (dll->state & 2) == 0) { if (_wcsicmp(ImageName, dll->nameW) == 0 && (dll->state & 2) == 0) {
if (LoadState) {
BOOLEAN ok = dll->init_func(ImageBase); BOOLEAN ok = dll->init_func(ImageBase);
if (!ok) if (!ok)
SbieApi_Log(2318, dll->nameW); SbieApi_Log(2318, dll->nameW);
} else {
break; SbieDll_UnHookModule(ImageBase);
} }
break;
++dll;
} }
++dll;
} }
} }
_FX void Ldr_MyDllCallbackNew(const WCHAR *ImageName, HMODULE ImageBase) _FX void Ldr_MyDllCallbackNew(const WCHAR *ImageName, HMODULE ImageBase, BOOL LoadState)
{ {
// //
// invoke our sub-modules as necessary // invoke our sub-modules as necessary
@ -1021,20 +1028,25 @@ _FX void Ldr_MyDllCallbackNew(const WCHAR *ImageName, HMODULE ImageBase)
while (dll->nameW) { while (dll->nameW) {
BOOLEAN ok; BOOLEAN ok;
if (_wcsicmp(ImageName, dll->nameW) == 0 && (dll->state & 2) == 0) { if (_wcsicmp(ImageName, dll->nameW) == 0 && (dll->state & 2) == 0) {
if (ImageBase && !dll->state) { if (LoadState) {
EnterCriticalSection(&Ldr_LoadedModules_CritSec); if (!dll->state) {
dll->state = 1; EnterCriticalSection(&Ldr_LoadedModules_CritSec);
LeaveCriticalSection(&Ldr_LoadedModules_CritSec); dll->state = 1;
ok = dll->init_func(ImageBase); LeaveCriticalSection(&Ldr_LoadedModules_CritSec);
if (!ok) ok = dll->init_func(ImageBase);
SbieApi_Log(2318, dll->nameW); if (!ok)
break; SbieApi_Log(2318, dll->nameW);
}
} }
else { else {
EnterCriticalSection(&Ldr_LoadedModules_CritSec); if (dll->state) {
dll->state = 0; SbieDll_UnHookModule(ImageBase);
LeaveCriticalSection(&Ldr_LoadedModules_CritSec); EnterCriticalSection(&Ldr_LoadedModules_CritSec);
dll->state = 0;
LeaveCriticalSection(&Ldr_LoadedModules_CritSec);
}
} }
break;
} }
++dll; ++dll;
} }

View File

@ -28,7 +28,7 @@
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
static BOOLEAN Lsa_Init_Common(const WCHAR *DllName); static BOOLEAN Lsa_Init_Common(const WCHAR *DllName, HMODULE module);
static NTSTATUS Lsa_LsaRegisterLogonProcess( static NTSTATUS Lsa_LsaRegisterLogonProcess(
void *LogonProcessName, HANDLE *LsaHandle, void *SecurityMode); void *LogonProcessName, HANDLE *LsaHandle, void *SecurityMode);
@ -59,7 +59,7 @@ static P_LsaRegisterLogonProcess __sys_LsaRegisterLogonProcess = NULL;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Lsa_Init_Common(const WCHAR *DllName) _FX BOOLEAN Lsa_Init_Common(const WCHAR *DllName, HMODULE module)
{ {
void *LsaRegisterLogonProcess; void *LsaRegisterLogonProcess;
@ -111,7 +111,7 @@ _FX BOOLEAN Lsa_Init_Secur32(HMODULE module)
return TRUE; return TRUE;
} }
return Lsa_Init_Common(DllName_secur32); return Lsa_Init_Common(DllName_secur32, module);
} }
@ -132,5 +132,5 @@ _FX BOOLEAN Lsa_Init_SspiCli(HMODULE module)
return TRUE; return TRUE;
} }
return Lsa_Init_Common(DllName_sspicli); return Lsa_Init_Common(DllName_sspicli, module);
} }

View File

@ -58,7 +58,7 @@ _FX DWORD MsCorEE__CorExeMain()
// Load inject dlls in .Net process's entry (_CorExeMain). // Load inject dlls in .Net process's entry (_CorExeMain).
_FX BOOLEAN MsCorEE_Init(HMODULE hmodule) _FX BOOLEAN MsCorEE_Init(HMODULE module)
{ {
// Use the code from AdvApi_Init // Use the code from AdvApi_Init

View File

@ -63,6 +63,8 @@ static P_NtQueryObject __sys_NtQueryObject = NULL;
_FX BOOLEAN Obj_Init(void) _FX BOOLEAN Obj_Init(void)
{ {
HMODULE module = NULL;
#if 0 #if 0
__sys_NtQueryObject = NtQueryObject; __sys_NtQueryObject = NtQueryObject;
#else #else

View File

@ -47,16 +47,16 @@ static P_PdhLookupPerfNameByIndexW __sys_PdhLookupPerfNameByIndexW = NULL;
// Pdh_Init // Pdh_Init
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Pdh_Init(HMODULE hDll) _FX BOOLEAN Pdh_Init(HMODULE module)
{ {
void * PdhConnectMachineW; void * PdhConnectMachineW;
void * PdhLookupPerfNameByIndexW; void * PdhLookupPerfNameByIndexW;
PdhConnectMachineW = (void*)GetProcAddress(hDll, "PdhConnectMachineW"); PdhConnectMachineW = (void*)GetProcAddress(module, "PdhConnectMachineW");
if (PdhConnectMachineW == NULL) if (PdhConnectMachineW == NULL)
return FALSE; return FALSE;
PdhLookupPerfNameByIndexW = (void*)GetProcAddress(hDll, "PdhLookupPerfNameByIndexW"); PdhLookupPerfNameByIndexW = (void*)GetProcAddress(module, "PdhLookupPerfNameByIndexW");
if (PdhLookupPerfNameByIndexW == NULL) if (PdhLookupPerfNameByIndexW == NULL)
return FALSE; return FALSE;

View File

@ -324,6 +324,8 @@ BOOL Dll_ElectronWorkaround = FALSE;
_FX BOOLEAN Proc_Init(void) _FX BOOLEAN Proc_Init(void)
{ {
HMODULE module = NULL;
P_CreateProcessInternal CreateProcessInternalW; P_CreateProcessInternal CreateProcessInternalW;
ANSI_STRING ansi; ANSI_STRING ansi;
NTSTATUS status; NTSTATUS status;

View File

@ -66,15 +66,18 @@ PROCESS_DATA *my_findProcessData(WCHAR *name,int createNew);
// Functions (DllMain) // Functions (DllMain)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
SBIEDLL_EXPORT void SbieDll_HookInit();
SBIEDLL_EXPORT void *SbieDll_Hook( SBIEDLL_EXPORT void *SbieDll_Hook(
const char *SourceFuncName, void *SourceFunc, void *DetourFunc); const char *SourceFuncName, void *SourceFunc, void *DetourFunc, HMODULE module);
#define SBIEDLL_HOOK(pfx,proc) \ #define SBIEDLL_HOOK(pfx,proc) \
*(ULONG_PTR *)&__sys_##proc = (ULONG_PTR) \ *(ULONG_PTR *)&__sys_##proc = (ULONG_PTR) \
SbieDll_Hook(#proc, proc, pfx##proc); \ SbieDll_Hook(#proc, proc, pfx##proc, module); \
if (! __sys_##proc) return FALSE; if (! __sys_##proc) return FALSE;
SBIEDLL_EXPORT void SbieDll_UnHookModule(HMODULE module);
SBIEDLL_EXPORT void SbieDll_DeviceChange(WPARAM wParam, LPARAM lParam); SBIEDLL_EXPORT void SbieDll_DeviceChange(WPARAM wParam, LPARAM lParam);
SBIEDLL_EXPORT const WCHAR *SbieDll_GetDrivePath(ULONG DriveIndex); SBIEDLL_EXPORT const WCHAR *SbieDll_GetDrivePath(ULONG DriveIndex);

View File

@ -48,7 +48,7 @@
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
static BOOLEAN Scm_HookRegisterServiceCtrlHandler(void); static BOOLEAN Scm_HookRegisterServiceCtrlHandler(HMODULE module);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@ -379,9 +379,9 @@ static const WCHAR *_TrustedInstaller = L"TrustedInstaller";
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
#define SBIEDLL_HOOK_SCM(proc) \ #define SBIEDLL_HOOK_SCM(proc) \
*(ULONG_PTR *)&__sys_##proc = (ULONG_PTR) \ *(ULONG_PTR *)&__sys_##proc = (ULONG_PTR) \
SbieDll_Hook(#proc, __sys_##proc, Scm_##proc); \ SbieDll_Hook(#proc, __sys_##proc, Scm_##proc, module); \
if (! __sys_##proc) return FALSE; if (! __sys_##proc) return FALSE;
@ -609,7 +609,7 @@ _FX BOOLEAN Scm_Init_AdvApi(HMODULE module)
Scm_Notify_Init(module); Scm_Notify_Init(module);
return Scm_HookRegisterServiceCtrlHandler(); return Scm_HookRegisterServiceCtrlHandler(module);
} }
@ -618,7 +618,7 @@ _FX BOOLEAN Scm_Init_AdvApi(HMODULE module)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
BOOLEAN Scm_HookRegisterServiceCtrlHandler(void) BOOLEAN Scm_HookRegisterServiceCtrlHandler(HMODULE module)
{ {
static const UCHAR PrologW[] = { static const UCHAR PrologW[] = {
0x45, 0x33, 0xC9, // xor r9d,r9d 0x45, 0x33, 0xC9, // xor r9d,r9d

View File

@ -156,7 +156,7 @@ _FX BOOLEAN Scm_SecHostDll(HMODULE module)
return FALSE; return FALSE;
} }
ResPtr = SbieDll_Hook((char *)funcNamesAW[i].FuncNameA, SecPtr, AdvPtr); ResPtr = SbieDll_Hook((char *)funcNamesAW[i].FuncNameA, SecPtr, AdvPtr, module);
if (! ResPtr) if (! ResPtr)
return FALSE; return FALSE;
} }

View File

@ -130,6 +130,7 @@ static HANDLE Msi_ServerInUseEvent = NULL;
_FX BOOLEAN Scm_SetupMsiHooks() _FX BOOLEAN Scm_SetupMsiHooks()
{ {
HMODULE module = NULL;
//while (!IsDebuggerPresent()) //while (!IsDebuggerPresent())
// Sleep(500); // Sleep(500);

View File

@ -362,6 +362,8 @@ void Secure_InitSecurityDescriptors(void)
_FX BOOLEAN Secure_Init(void) _FX BOOLEAN Secure_Init(void)
{ {
HMODULE module = NULL;
void *RtlQueryElevationFlags; void *RtlQueryElevationFlags;
void *RtlCheckTokenMembershipEx; void *RtlCheckTokenMembershipEx;

View File

@ -136,15 +136,15 @@ static P_CM_Add_Driver_Package_ExW __sys_CM_Add_Driver_Package_ExW = NULL;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
#define DO_CALL_HOOK(name,devName) \ #define DO_CALL_HOOK(name,devName) \
__sys_##name = SbieDll_Hook(#name, __sys_##name, devName); \ __sys_##name = SbieDll_Hook(#name, __sys_##name, devName, module); \
if (! __sys_##name) return FALSE; if (! __sys_##name) return FALSE;
#define HOOK_AW(func) \ #define HOOK_AW(func) \
DO_CALL_HOOK(func##A,Dev_##func##A); \ DO_CALL_HOOK(func##A,Dev_##func##A); \
DO_CALL_HOOK(func##W,Dev_##func##W); DO_CALL_HOOK(func##W,Dev_##func##W);
#define HOOK(func) \ #define HOOK(func) \
DO_CALL_HOOK(func,Dev_##func); DO_CALL_HOOK(func,Dev_##func);
#define FIND_EP(x) __sys_##x = (P_##x) GetProcAddress(module, #x) #define FIND_EP(x) __sys_##x = (P_##x) GetProcAddress(module, #x)

View File

@ -1046,7 +1046,7 @@ _FX BOOLEAN SH32_Init(HMODULE module)
*(ULONG_PTR *)&__sys_LdrGetDllHandleEx = (ULONG_PTR) *(ULONG_PTR *)&__sys_LdrGetDllHandleEx = (ULONG_PTR)
SbieDll_Hook("LdrGetDllHandleEx", SbieDll_Hook("LdrGetDllHandleEx",
__sys_LdrGetDllHandleEx, SH32_LdrGetDllHandleEx); __sys_LdrGetDllHandleEx, SH32_LdrGetDllHandleEx, module);
} }
// //

View File

@ -122,6 +122,8 @@ BOOLEAN SysInfo_CanUseJobs = FALSE;
_FX BOOLEAN SysInfo_Init(void) _FX BOOLEAN SysInfo_Init(void)
{ {
HMODULE module = NULL;
void *NtTraceEvent; void *NtTraceEvent;
if (! Dll_SkipHook(L"ntqsi")) { if (! Dll_SkipHook(L"ntqsi")) {

View File

@ -61,6 +61,8 @@ static P_OutputDebugString __sys_OutputDebugStringA = NULL;
_FX int Trace_Init(void) _FX int Trace_Init(void)
{ {
HMODULE module = NULL; // fix-me
P_RtlSetLastWin32Error RtlSetLastWin32Error; P_RtlSetLastWin32Error RtlSetLastWin32Error;
P_OutputDebugString OutputDebugStringW; P_OutputDebugString OutputDebugStringW;
P_OutputDebugString OutputDebugStringA; P_OutputDebugString OutputDebugStringA;

View File

@ -1301,9 +1301,7 @@ _FX NTSTATUS Api_QueryDriverInfo(PROCESS* proc, ULONG64* parms)
if (Obj_CallbackInstalled) if (Obj_CallbackInstalled)
FeatureFlags |= SBIE_FEATURE_FLAG_OB_CALLBACKS; FeatureFlags |= SBIE_FEATURE_FLAG_OB_CALLBACKS;
extern UCHAR SandboxieLogonSid[SECURITY_MAX_SID_SIZE]; FeatureFlags |= SBIE_FEATURE_FLAG_SBIE_LOGIN;
if (SandboxieLogonSid[0] != 0)
FeatureFlags |= SBIE_FEATURE_FLAG_SBIE_LOGIN;
#ifdef HOOK_WIN32K #ifdef HOOK_WIN32K
extern ULONG Syscall_MaxIndex32; extern ULONG Syscall_MaxIndex32;

View File

@ -1468,12 +1468,6 @@ _FX NTSTATUS Conf_Api_Reload(PROCESS *proc, ULONG64 *parms)
} }
} }
extern UCHAR SandboxieLogonSid[SECURITY_MAX_SID_SIZE];
if (Conf_Get_Boolean(NULL, L"AllowSandboxieLogon", 0, FALSE) && SandboxieLogonSid[0] == 0) {
extern BOOLEAN Token_Init_SbieLogin(void);
Token_Init_SbieLogin();
}
/* /*
#ifdef HOOK_WIN32K #ifdef HOOK_WIN32K
// must be windows 10 or later // must be windows 10 or later

View File

@ -267,8 +267,6 @@ _FX void Log_Msg_Process(
ULONG session_id, ULONG session_id,
HANDLE process_id) HANDLE process_id)
{ {
DbgPrint("Sbie MSG_%d: %S; %S\r\n", (error_code & 0xFFFF), string1, string2);
ULONG facility = (error_code >> 16) & 0x0F; ULONG facility = (error_code >> 16) & 0x0F;
if (facility & MSG_FACILITY_EVENT) if (facility & MSG_FACILITY_EVENT)
Log_Event_Msg(error_code, string1, string2); Log_Event_Msg(error_code, string1, string2);

View File

@ -96,6 +96,8 @@ struct _PROCESS {
void *primary_token; void *primary_token;
PSID *SandboxieLogonSid;
// thread data // thread data
PERESOURCE threads_lock; PERESOURCE threads_lock;

View File

@ -262,6 +262,23 @@ _FX NTSTATUS Process_Low_Api_InjectComplete(PROCESS *proc, ULONG64 *parms)
if (proc) { if (proc) {
__try {
PSID pSID = (PSID)(ULONG_PTR)parms[2];
if (pSID) {
ProbeForRead(pSID, SECURITY_MAX_SID_SIZE, sizeof(UCHAR));
ULONG sid_length = RtlLengthSid(pSID);
proc->SandboxieLogonSid = Mem_Alloc(proc->pool, sid_length);
memcpy(proc->SandboxieLogonSid, pSID, sid_length);
}
} __except (EXCEPTION_EXECUTE_HANDLER) {
status = GetExceptionCode();
}
KeSetEvent(Process_Low_Event, 0, FALSE); KeSetEvent(Process_Low_Event, 0, FALSE);
status = STATUS_SUCCESS; status = STATUS_SUCCESS;

View File

@ -51,8 +51,6 @@ NTSTATUS Sbie_SepFilterToken_KernelMode(
void **NewToken void **NewToken
); );
BOOLEAN Token_Init_SbieLogin(void);
static BOOLEAN Token_Init_SepFilterToken(void); static BOOLEAN Token_Init_SepFilterToken(void);
static void *Token_FilterPrimary(PROCESS *proc, void *ProcessObject); static void *Token_FilterPrimary(PROCESS *proc, void *ProcessObject);
@ -150,7 +148,7 @@ static UCHAR AnonymousLogonSid[12] = {
SECURITY_ANONYMOUS_LOGON_RID,0,0,0 // SubAuthority SECURITY_ANONYMOUS_LOGON_RID,0,0,0 // SubAuthority
}; };
UCHAR SandboxieLogonSid[SECURITY_MAX_SID_SIZE] = { 0 }; // SbieLogin //UCHAR SandboxieLogonSid[SECURITY_MAX_SID_SIZE] = { 0 }; // SbieLogin
static UCHAR SystemLogonSid[12] = { static UCHAR SystemLogonSid[12] = {
1, // Revision 1, // Revision
@ -221,15 +219,6 @@ _FX BOOLEAN Token_Init(void)
#undef MySetGroup #undef MySetGroup
//
// find the sid of the sandboxie user if present
//
// SbieLogin BEGIN
if (Conf_Get_Boolean(NULL, L"AllowSandboxieLogon", 0, FALSE))
Token_Init_SbieLogin();
// SbieLogin END
// //
// find SepFilterToken for Token_RestrictHelper1 // find SepFilterToken for Token_RestrictHelper1
// //
@ -252,27 +241,27 @@ _FX BOOLEAN Token_Init(void)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
_FX BOOLEAN Token_Init_SbieLogin(void) //_FX BOOLEAN Token_Init_SbieLogin(void)
{ //{
WCHAR AccountBuffer[64]; // DNLEN + 1 + sizeof(SANDBOXIE_USER) + reserve // WCHAR AccountBuffer[64]; // DNLEN + 1 + sizeof(SANDBOXIE_USER) + reserve
UNICODE_STRING AccountName = { 0, sizeof(AccountBuffer), AccountBuffer }; // Note: max valid length is (DNLEN (15) + 1) * sizeof(WCHAR), length is in bytes leave half empty // UNICODE_STRING AccountName = { 0, sizeof(AccountBuffer), AccountBuffer }; // Note: max valid length is (DNLEN (15) + 1) * sizeof(WCHAR), length is in bytes leave half empty
if (GetRegString(RTL_REGISTRY_ABSOLUTE, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName", L"ComputerName", &AccountName) && AccountName.Length < 64) // if (NT_SUCCESS(GetRegString(RTL_REGISTRY_ABSOLUTE, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName", L"ComputerName", &AccountName)) && AccountName.Length < 64)
{ // {
wcscpy(AccountName.Buffer + (AccountName.Length / sizeof(WCHAR)), L"\\" SANDBOXIE_USER); // wcscpy(AccountName.Buffer + (AccountName.Length / sizeof(WCHAR)), L"\\" SANDBOXIE_USER);
AccountName.Length += (1 + wcslen(SANDBOXIE_USER)) * sizeof(WCHAR); // AccountName.Length += (1 + wcslen(SANDBOXIE_USER)) * sizeof(WCHAR);
//DbgPrint("Sbie, AccountName: %S\n", AccountName.Buffer); // //DbgPrint("Sbie, AccountName: %S\n", AccountName.Buffer);
//
SID_NAME_USE use; // SID_NAME_USE use;
ULONG userSize = sizeof(SandboxieLogonSid), domainSize = 0; // ULONG userSize = sizeof(SandboxieLogonSid), domainSize = 0;
WCHAR DomainBuff[20]; // doesn't work without this // WCHAR DomainBuff[20]; // doesn't work without this
UNICODE_STRING DomainName = { 0, sizeof(DomainBuff), DomainBuff }; // UNICODE_STRING DomainName = { 0, sizeof(DomainBuff), DomainBuff };
//
SecLookupAccountName(&AccountName, &userSize, (PSID)SandboxieLogonSid, &use, &domainSize, &DomainName); // SecLookupAccountName(&AccountName, &userSize, (PSID)SandboxieLogonSid, &use, &domainSize, &DomainName);
//DbgPrint("Sbie, SecLookupAccountName: %x; size:%d %d\n", status, userSize, domainSize); // //DbgPrint("Sbie, SecLookupAccountName: %x; size:%d %d\n", status, userSize, domainSize);
} // }
//
return TRUE; // return TRUE;
} //}
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@ -1009,7 +998,7 @@ _FX BOOLEAN Token_ResetPrimary(PROCESS *proc)
((ULONG_PTR)TokenObject + UserAndGroups_offset); ((ULONG_PTR)TokenObject + UserAndGroups_offset);
// Windows 8.1 update // Windows 8.1 update
if (SidAndAttrsInToken->Sid == (PSID)AnonymousLogonSid || SidAndAttrsInToken->Sid == (PSID)SandboxieLogonSid) if (SidAndAttrsInToken->Sid == (PSID)proc->SandboxieLogonSid)
{ {
//DbgPrint("Sbie, restore token pointer\n"); //DbgPrint("Sbie, restore token pointer\n");
@ -1270,27 +1259,12 @@ _FX void *Token_RestrictHelper1(
UCHAR *SidInToken = (UCHAR *)SidAndAttrsInToken->Sid; UCHAR *SidInToken = (UCHAR *)SidAndAttrsInToken->Sid;
if (SidInToken && SidInToken[1] >= 1) { // SubAuthorityCount >= 1 if (SidInToken && SidInToken[1] >= 1) { // SubAuthorityCount >= 1
PSID NewSid = NULL; if (!proc->SandboxieLogonSid && Conf_Get_Boolean(proc->box->name, L"AnonymousLogon", 0, TRUE))
// SbieLogin BEGIN
if (Conf_Get_Boolean(proc->box->name, L"SandboxieLogon", 0, FALSE))
{
if (SandboxieLogonSid[0] != 0)
NewSid = (PSID)SandboxieLogonSid;
else
status = STATUS_UNSUCCESSFUL;
}
else
// SbieLogin END
// debug tip. To disable anonymous logon, set AnonymousLogon=n
if (Conf_Get_Boolean(proc->box->name, L"AnonymousLogon", 0, TRUE))
{ {
NewSid = (PSID)AnonymousLogonSid; proc->SandboxieLogonSid = (PSID)AnonymousLogonSid;
} }
if (NewSid != NULL) if (proc->SandboxieLogonSid)
{ {
// In windows 8.1 Sid can be in two difference places. One is relative to SidAndAttrsInToken. // In windows 8.1 Sid can be in two difference places. One is relative to SidAndAttrsInToken.
// By debugger, the offset is 0xf0 after SidAndAttrsInToken. The other one is with KB2919355, // By debugger, the offset is 0xf0 after SidAndAttrsInToken. The other one is with KB2919355,
@ -1306,14 +1280,14 @@ _FX void *Token_RestrictHelper1(
// When trying apply the SbieLogin token to a system process there is not enough space in the SID // When trying apply the SbieLogin token to a system process there is not enough space in the SID
// so we need to use a workaround not unlike the one for win 8 // so we need to use a workaround not unlike the one for win 8
|| (RtlLengthSid(SidInToken) < RtlLengthSid(NewSid)) || (RtlLengthSid(SidInToken) < RtlLengthSid(proc->SandboxieLogonSid))
) { ) {
//DbgPrint("Sbie, hack token pointer\n"); //DbgPrint("Sbie, hack token pointer\n");
SidAndAttrsInToken->Sid = (PSID)NewSid; SidAndAttrsInToken->Sid = proc->SandboxieLogonSid;
} }
else { else {
memcpy(SidInToken, NewSid, RtlLengthSid(NewSid)); memcpy(SidInToken, proc->SandboxieLogonSid, RtlLengthSid(proc->SandboxieLogonSid));
} }
} }
} }
@ -2250,15 +2224,15 @@ _FX void* Token_CreateNew(void* TokenObject, PROCESS* proc)
PTOKEN_SOURCE LocalSource = NULL; PTOKEN_SOURCE LocalSource = NULL;
PTOKEN_DEFAULT_DACL NewDefaultDacl = NULL; PTOKEN_DEFAULT_DACL NewDefaultDacl = NULL;
ULONG DefaultDacl_Length = 0; PTOKEN_OWNER NewOwner = NULL;
PACL Dacl = NULL; ULONG DefaultDacl_Length = 0;
PSID Sid = NULL; PACL NewDacl = NULL;
OBJECT_ATTRIBUTES ObjectAttributes; OBJECT_ATTRIBUTES ObjectAttributes;
SECURITY_QUALITY_OF_SERVICE SecurityQos; SECURITY_QUALITY_OF_SERVICE SecurityQos;
// //
// Gather information from the original token // Gether informations from the original token
// //
if ( !NT_SUCCESS(SeQueryInformationToken(TokenObject, TokenStatistics, &LocalStatistics)) if ( !NT_SUCCESS(SeQueryInformationToken(TokenObject, TokenStatistics, &LocalStatistics))
@ -2283,26 +2257,14 @@ _FX void* Token_CreateNew(void* TokenObject, PROCESS* proc)
// Change the SID // Change the SID
// //
// SbieLogin BEGIN if (!proc->SandboxieLogonSid && Conf_Get_Boolean(proc->box->name, L"AnonymousLogon", 0, TRUE))
if (Conf_Get_Boolean(proc->box->name, L"SandboxieLogon", 0, FALSE))
{
if (SandboxieLogonSid[0] != 0)
Sid = (PSID)SandboxieLogonSid;
else {
Log_Status_Ex_Process(MSG_1222, 0xA6, status, NULL, proc->box->session_id, proc->pid);
goto finish;
}
}
else
// SbieLogin END
if (Conf_Get_Boolean(proc->box->name, L"AnonymousLogon", 0, TRUE))
{ {
Sid = (PSID)AnonymousLogonSid; proc->SandboxieLogonSid = (PSID)AnonymousLogonSid;
} }
if (Sid != NULL) if (proc->SandboxieLogonSid)
{ {
memcpy(LocalUser->User.Sid, Sid, RtlLengthSid(Sid)); memcpy(LocalUser->User.Sid, proc->SandboxieLogonSid, RtlLengthSid(proc->SandboxieLogonSid));
} }
// //
@ -2324,6 +2286,8 @@ _FX void* Token_CreateNew(void* TokenObject, PROCESS* proc)
NULL NULL
); );
//LUID AuthenticationId = ANONYMOUS_LOGON_LUID;
status = SbieCreateToken( status = SbieCreateToken(
&TokenHandle, &TokenHandle,
TOKEN_ALL_ACCESS, TOKEN_ALL_ACCESS,
@ -2350,7 +2314,7 @@ _FX void* Token_CreateNew(void* TokenObject, PROCESS* proc)
// Retry with new DACLs on error // Retry with new DACLs on error
// //
if (Sid && status == STATUS_INVALID_OWNER) if (proc->SandboxieLogonSid && status == STATUS_INVALID_OWNER)
{ {
DefaultDacl_Length = LocalDefaultDacl->DefaultDacl->AclSize; DefaultDacl_Length = LocalDefaultDacl->DefaultDacl->AclSize;
@ -2364,11 +2328,13 @@ _FX void* Token_CreateNew(void* TokenObject, PROCESS* proc)
memcpy(NewDefaultDacl, LocalDefaultDacl, DefaultDacl_Length); memcpy(NewDefaultDacl, LocalDefaultDacl, DefaultDacl_Length);
NewDefaultDacl->DefaultDacl = Dacl = (PACL)((ULONG_PTR)NewDefaultDacl + sizeof(TOKEN_DEFAULT_DACL)); NewDefaultDacl->DefaultDacl = NewDacl = (PACL)((ULONG_PTR)NewDefaultDacl + sizeof(TOKEN_DEFAULT_DACL));
NewDefaultDacl->DefaultDacl->AclSize += 128; NewDefaultDacl->DefaultDacl->AclSize += 128;
Sid = LocalUser->User.Sid;
RtlAddAccessAllowedAce(Dacl, ACL_REVISION2, GENERIC_ALL, Sid); NewOwner = (PTOKEN_OWNER)ExAllocatePoolWithTag(PagedPool, sizeof(TOKEN_OWNER), tzuk);
NewOwner->Owner = LocalUser->User.Sid;
RtlAddAccessAllowedAce(NewDacl, ACL_REVISION2, GENERIC_ALL, NewOwner->Owner);
status = SbieCreateToken( status = SbieCreateToken(
&TokenHandle, &TokenHandle,
@ -2386,7 +2352,7 @@ _FX void* Token_CreateNew(void* TokenObject, PROCESS* proc)
0, //DeviceGroups, 0, //DeviceGroups,
MandatoryPolicy, MandatoryPolicy,
(PTOKEN_OWNER)&Sid, NewOwner,
LocalPrimaryGroup, LocalPrimaryGroup,
NewDefaultDacl, NewDefaultDacl,
LocalSource LocalSource
@ -2398,9 +2364,9 @@ _FX void* Token_CreateNew(void* TokenObject, PROCESS* proc)
goto finish; goto finish;
} }
Token_SetHandleDacl(NtCurrentProcess(), Dacl); Token_SetHandleDacl(NtCurrentProcess(), NewDacl);
Token_SetHandleDacl(NtCurrentThread(), Dacl); Token_SetHandleDacl(NtCurrentThread(), NewDacl);
Token_SetHandleDacl(TokenHandle, Dacl); Token_SetHandleDacl(TokenHandle, NewDacl);
} }
else if (!NT_SUCCESS(status)) else if (!NT_SUCCESS(status))
{ {
@ -2467,6 +2433,7 @@ finish:
if (LocalSource) ExFreePool((PVOID)LocalSource); if (LocalSource) ExFreePool((PVOID)LocalSource);
if (NewDefaultDacl) ExFreePool((PVOID)NewDefaultDacl); if (NewDefaultDacl) ExFreePool((PVOID)NewDefaultDacl);
if (NewOwner) ExFreePool((PVOID)NewOwner);
// //

View File

@ -234,6 +234,8 @@ void DriverAssist::ShutdownPortAndThreads()
if (PortHandle) if (PortHandle)
NtClose(PortHandle); NtClose(PortHandle);
CleanUpSIDs();
} }

View File

@ -112,6 +112,14 @@ private:
void InjectLow(void *_msg); void InjectLow(void *_msg);
HANDLE InjectLow_OpenProcess(void *_msg); HANDLE InjectLow_OpenProcess(void *_msg);
//
// SbieLogin
//
bool GetSandboxieSID(const WCHAR* boxname, UCHAR* SandboxieLogonSid, DWORD dwSidSize);
void CleanUpSIDs();
// //
// data // data
// //

View File

@ -55,7 +55,9 @@ void DriverAssist::InjectLow(void *_msg)
{ {
SVC_PROCESS_MSG *msg = (SVC_PROCESS_MSG *)_msg; SVC_PROCESS_MSG *msg = (SVC_PROCESS_MSG *)_msg;
NTSTATUS status = 0;
ULONG errlvl = 0; ULONG errlvl = 0;
UCHAR SandboxieLogonSid[SECURITY_MAX_SID_SIZE] = { 0 };
// //
// open new process and verify process creation time // open new process and verify process creation time
@ -115,7 +117,12 @@ void DriverAssist::InjectLow(void *_msg)
// notify driver that we successfully injected the lowlevel code // notify driver that we successfully injected the lowlevel code
// //
if (SbieApi_Call(API_INJECT_COMPLETE, 1, (ULONG_PTR)msg->process_id) == 0) if (GetSandboxieSID(boxname, SandboxieLogonSid, sizeof(SandboxieLogonSid)))
status = SbieApi_Call(API_INJECT_COMPLETE, 2, (ULONG_PTR)msg->process_id, SandboxieLogonSid);
else // if that fails or is not enabled we fall back to using the anonymous logon token
status = SbieApi_Call(API_INJECT_COMPLETE, 1, (ULONG_PTR)msg->process_id);
if (status == 0)
errlvl = 0; errlvl = 0;
else else
errlvl = 0x99; errlvl = 0x99;

View File

@ -0,0 +1,154 @@
/*
* Copyright 2022 David Xanatos, xanasoft.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// Driver Assistant
//---------------------------------------------------------------------------
#include "stdafx.h"
#include "DriverAssist.h"
#include <ntsecapi.h>
#include "common/lsalookupi_ddk.h"
#include "common/my_Version.h"
extern "C" {
NTSTATUS WINAPI LsaManageSidNameMapping(
_In_ LSA_SID_NAME_MAPPING_OPERATION_TYPE OpType,
_In_ PLSA_SID_NAME_MAPPING_OPERATION_INPUT OpInput,
_Out_ PLSA_SID_NAME_MAPPING_OPERATION_OUTPUT* OpOutput
);
NTSTATUS NTAPI RtlCreateVirtualAccountSid(
_In_ PUNICODE_STRING Name,
_In_ ULONG BaseSubAuthority,
_Out_ PSID Sid,
_Inout_ PULONG SidLength
);
__declspec(dllimport) NTSTATUS __stdcall RtlInitUnicodeString(
PUNICODE_STRING DestinationString,
const WCHAR* SourceString
);
#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)
}
NTSTATUS AddSidName(PSID pSID, const WCHAR* domain, const WCHAR* user)
{
NTSTATUS status;
LSA_SID_NAME_MAPPING_OPERATION_ADD_INPUT add_input;
memset(&add_input, 0, sizeof(LSA_SID_NAME_MAPPING_OPERATION_ADD_INPUT));
PLSA_SID_NAME_MAPPING_OPERATION_INPUT input = (PLSA_SID_NAME_MAPPING_OPERATION_INPUT)&add_input;
PLSA_SID_NAME_MAPPING_OPERATION_OUTPUT output = NULL;
add_input.Sid = pSID;
add_input.Flags = 0;
RtlInitUnicodeString(&add_input.DomainName, domain);
if(user != NULL)
RtlInitUnicodeString(&add_input.AccountName, user);
status = LsaManageSidNameMapping(LsaSidNameMappingOperation_Add, input, &output);
if(output)
LsaFreeMemory(output);
return status;
}
NTSTATUS RemoveSidName(const WCHAR* domain, const WCHAR* user)
{
NTSTATUS status;
_LSA_SID_NAME_MAPPING_OPERATION_REMOVE_INPUT add_input;
memset(&add_input, 0, sizeof(_LSA_SID_NAME_MAPPING_OPERATION_REMOVE_INPUT));
PLSA_SID_NAME_MAPPING_OPERATION_INPUT input = (PLSA_SID_NAME_MAPPING_OPERATION_INPUT)&add_input;
PLSA_SID_NAME_MAPPING_OPERATION_OUTPUT output = NULL;
RtlInitUnicodeString(&add_input.DomainName, domain);
if(user != NULL)
RtlInitUnicodeString(&add_input.AccountName, user);
status = LsaManageSidNameMapping(LsaSidNameMappingOperation_Add, input, &output);
if(output)
LsaFreeMemory(output);
return status;
}
#define SBIE_RID 100 // must be between 80 and 111 inclusive
UCHAR SandboxieSid[12] = {
1, // Revision
1, // SubAuthorityCount
0,0,0,0,0,5, // SECURITY_NT_AUTHORITY // IdentifierAuthority
SBIE_RID,0,0,0 // SubAuthority
};
//---------------------------------------------------------------------------
// GetSandboxieSID
//---------------------------------------------------------------------------
bool DriverAssist::GetSandboxieSID(const WCHAR* boxname, UCHAR* pSID, DWORD dwSidSize)
{
if (!SbieApi_QueryConfBool(boxname, L"SandboxieLogon", TRUE))
return false;
WCHAR szUserName[256], szDomainName[256];
DWORD dwDomainSize = ARRAYSIZE(szDomainName);
SID_NAME_USE snu = SidTypeInvalid;
wcscpy(szUserName, SANDBOXIE L"\\");
wcscat(szUserName, boxname);
if (LookupAccountName(NULL, szUserName, pSID, &dwSidSize, szDomainName, &dwDomainSize, &snu))
return true;
//
// add Sandboxie domain "Sandboxie"
//
static bool SbieAdded = false;
if (!SbieAdded) {
AddSidName(SandboxieSid, SANDBOXIE, NULL);
SbieAdded = true;
}
//
// add Sandboxie box user "Sandboxie\\DefaultBox"
//
UNICODE_STRING Name;
RtlInitUnicodeString(&Name, boxname);
RtlCreateVirtualAccountSid(&Name, SBIE_RID, pSID, &dwSidSize);
return NT_SUCCESS(AddSidName(pSID, SANDBOXIE, boxname));
}
//---------------------------------------------------------------------------
// CleanUpSIDs
//---------------------------------------------------------------------------
void DriverAssist::CleanUpSIDs()
{
RemoveSidName(SANDBOXIE, NULL);
}

View File

@ -967,6 +967,8 @@ BOOL ProcessServer::RunSandboxedSetDacl(
SECURITY_ANONYMOUS_LOGON_RID,0,0,0 // SubAuthority SECURITY_ANONYMOUS_LOGON_RID,0,0,0 // SubAuthority
}; };
extern UCHAR SandboxieSid[12];
ULONG LastError; ULONG LastError;
HANDLE hToken; HANDLE hToken;
ULONG len; ULONG len;
@ -1006,7 +1008,7 @@ BOOL ProcessServer::RunSandboxedSetDacl(
ok = GetTokenInformation(hToken, TokenUser, pUser, 512, &len); ok = GetTokenInformation(hToken, TokenUser, pUser, 512, &len);
LastError = GetLastError(); LastError = GetLastError();
if (idProcess != NULL) // this is used when starting a service if (ok && idProcess != NULL) // this is used when starting a service
{ {
// //
// in Sandboxie version 4, the primary process token is going to be // in Sandboxie version 4, the primary process token is going to be
@ -1014,8 +1016,16 @@ BOOL ProcessServer::RunSandboxedSetDacl(
// textual SID string and convert it into a SID value // textual SID string and convert it into a SID value
// //
if (ok && memcmp(pUser->User.Sid, AnonymousLogonSid, //
sizeof(AnonymousLogonSid)) == 0) { // in Sandboxie version 5.57 instead of using the anonymous SID
// we can use box specific custom SIDs,
// when comparing we skip the revision and the SubAuthorityCount
// also we conpare only teh domain portion of the SID as the rest
// will be different for each box
//
if (memcmp(pUser->User.Sid, AnonymousLogonSid, sizeof(AnonymousLogonSid)) == 0
|| memcmp(((UCHAR*)pUser->User.Sid) + 2, SandboxieSid, 10) == 0) {
PSID TempSid; PSID TempSid;
WCHAR SidString[96]; WCHAR SidString[96];

View File

@ -245,6 +245,7 @@
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='SbieDebug|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='SbieDebug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='SbieRelease|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='SbieRelease|x64'">true</ExcludedFromBuild>
</ClCompile> </ClCompile>
<ClCompile Include="DriverAssistSid.cpp" />
<ClCompile Include="DriverAssistStart.cpp"> <ClCompile Include="DriverAssistStart.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='SbieDebug|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='SbieDebug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='SbieRelease|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='SbieRelease|Win32'">true</ExcludedFromBuild>

View File

@ -75,6 +75,9 @@
<ClCompile Include="comserver2.cpp"> <ClCompile Include="comserver2.cpp">
<Filter>ComProxy</Filter> <Filter>ComProxy</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="DriverAssistSid.cpp">
<Filter>DriverAssist</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="misc.h" /> <ClInclude Include="misc.h" />

View File

@ -1,8 +1,8 @@
#pragma once #pragma once
#define VERSION_MJR 1 #define VERSION_MJR 1
#define VERSION_MIN 1 #define VERSION_MIN 2
#define VERSION_REV 1 #define VERSION_REV 0
#define VERSION_UPD 0 #define VERSION_UPD 0
#ifndef STR #ifndef STR