SlideShare a Scribd company logo
1 of 84
Download to read offline
The Joy of
Sandbox Mitigations
James Forshaw @tiraniddo
Troopers 2016
1
James Forshaw @tiraniddo
What I’m Going to Talk About
● Sandbox related mitigations added to Windows since Windows 8
● Hardcore reverse engineering of the implementation
● What’s supported and how you can use them yourself
● What is blocked if you’re investigating sandbox attack surface
● Weird bugs and edge cases with the implementation
● Research on Windows 8.1 and 10 build 10586
2
James Forshaw @tiraniddo
WARNING
A huge amount of code snippets is approaching.
Sorry?
3
James Forshaw @tiraniddo
In the Beginning was DEP
4
James Forshaw @tiraniddo
The External Attacker’s Viewpoint
5
Mitigations:
DEP
ASLR
SafeSEH
Stack Cookies
Control Flow Guard (CFG)
etc.
System Services
Kernel Services Device Drivers
Prevent RCETarget Process
James Forshaw @tiraniddo
The Defender’s Dilemma
Assume Compromise
6
James Forshaw @tiraniddo
Sandboxing to the Rescue?
7
Sandboxed Target Process
User Applications
System Services
Kernel Services Device Drivers
Prevent RCE
PreventEoP
James Forshaw @tiraniddo
Technical Mitigations
8
Reduce Attack
Surface
Increase Exploit
Cost
Reduce Exploit
Reliability
James Forshaw @tiraniddo
Technical Mitigations
9
Reduce Attack
Surface
Increase Exploit
Cost
Reduce Exploit
Reliability
$ $
James Forshaw @tiraniddo
Technical Mitigations
10
Reduce Attack
Surface
Increase Exploit
Cost
Reduce Exploit
Reliability
James Forshaw @tiraniddo
Categories of Windows Sandbox Mitigations
Implicit Mitigations
● On by default when running
sandboxed code
● Applies to select features
which shouldn’t affect typical
backwards compatibility
support
● Focus more on breaking
chains and making
exploitation harder
11
Explicit Mitigations
● Mitigations which must be
actively enabled
● Usually more disruptive,
requires changes to existing
code to support
● Aim to reduce attack surface
or increase exploitation costs
James Forshaw @tiraniddo
Explicit Mitigations
12
James Forshaw @tiraniddo
Setting an Explicit Mitigation Policy
13
Policy Type
Accompanying Data
James Forshaw @tiraniddo
PROCESS_MITIGATION_POLICY
14
Policy Supported Win8.1 Update 2 Supported Win10 TH2
ProcessDEPPolicy Yes Yes
ProcessASLRPolicy Yes Yes
ProcessDynamicCodePolicy Yes Yes
ProcessStrictHandleCheckPolicy Yes Yes
ProcessSystemCallDisablePolicy Yes Yes
ProcessMitigationOptionsMask Invalid Invalid
ProcessExtensionPointDisablePolicy Yes Yes
ProcessControlFlowGuardPolicy Invalid Invalid
ProcessSignaturePolicy Yes* Yes
ProcessFontDisablePolicy No Yes
ProcessImageLoadPolicy No Yes
* Not supported through SetProcessMitigationPolicy
James Forshaw @tiraniddo
PROCESS_MITIGATION_POLICY
15
Policy Supported Win8.1 Update 2 Supported Win10 TH2
ProcessDEPPolicy Yes Yes
ProcessASLRPolicy Yes Yes
ProcessDynamicCodePolicy Yes Yes
ProcessStrictHandleCheckPolicy Yes Yes
ProcessSystemCallDisablePolicy Yes Yes
ProcessMitigationOptionsMask Invalid Invalid
ProcessExtensionPointDisablePolicy Yes Yes
ProcessControlFlowGuardPolicy Invalid Invalid
ProcessSignaturePolicy Yes* Yes
ProcessFontDisablePolicy No Yes
ProcessImageLoadPolicy No Yes
* Not supported through SetProcessMitigationPolicy
James Forshaw @tiraniddo
Under the Hood
const int ProcessMitigationPolicy = 52;
struct PROCESS_MITIGATION {
PROCESS_MITIGATION_POLICY Policy;
DWORD Flags;
};
PROCESS_MITIGATION m = {ProcessSignaturePolicy, 1};
NtSetInformationProcess(GetCurrentProcess(),
ProcessMitigationPolicy, &m, sizeof(m));
16
James Forshaw @tiraniddo
Under the Hood
const int ProcessMitigationPolicy = 52;
struct PROCESS_MITIGATION {
PROCESS_MITIGATION_POLICY Policy;
DWORD Flags;
};
PROCESS_MITIGATION m = {ProcessSignaturePolicy, 1};
NtSetInformationProcess(GetCurrentProcess(),
ProcessMitigationPolicy, &m, sizeof(m));
17
Can’t specify anything other
than current process, it will fail.
James Forshaw @tiraniddo
Apply During Create Process
LPPROC_THREAD_ATTRIBUTE_LIST attr_list = ... // Allocated
InitializeProcThreadAttributeList(attr_list, 1, 0, &size);
DWORD64 policy = PROCESS_CREATION_MITIGATION_POLICY_...;
UpdateProcThreadAttribute(attr_list, 0,
PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY, &policy,
sizeof(policy), nullptr, nullptr);
startInfo.StartupInfo.cb = sizeof(startInfo);
startInfo.lpAttributeList = attr_list;
// Create Process with EXTENDED_STARTUPINFO_PRESENT flag
18
I’ll abbreviate PROCESS_CREATION_MITIGATION_POLICY to PCMP otherwise it gets too long
Process Attribute for Mitigation Policy
James Forshaw @tiraniddo
Image File Execution Options
● Specify REG_QWORD value MitigationOptions with same bit fields
as used at process creation.
19
Registry Value
Executable Name
James Forshaw @tiraniddo
Image File Execution Options Filter
20
James Forshaw @tiraniddo
Demo Time!
Simple Mitigation Tests
21
James Forshaw @tiraniddo
Dynamic Code Policy
struct PROCESS_MITIGATION_DYNAMIC_CODE_POLICY {
union {
DWORD Flags;
struct {
DWORD ProhibitDynamicCode : 1;
DWORD ReservedFlags : 31;
};
};
}
PCMP_PROHIBIT_DYNAMIC_CODE_ALWAYS_ON (1 << 36)
22
Category: Increase Exploit Cost, Reduce Reliability
James Forshaw @tiraniddo
What Does it Disable?
● Calling VirtualAlloc with PAGE_EXECUTE_*
● MapViewOfFile with FILE_MAP_EXECUTE option
● Calling VirtualProtect with PAGE_EXECUTE_* etc.
● Reconfiguring the CFG bitmap via SetProcessValidCallTargets
23
It doesn’t disable loading
DLLs/Image Sections!
James Forshaw @tiraniddo
Under the Hood
NTSTATUS MiArbitraryCodeBlocked(EPROCESS *Process) {
if (Process->Flags2 & DYNAMIC_CODE_BLOCKED_FLAG)
return STATUS_DYNAMIC_CODE_BLOCKED;
return STATUS_SUCCESS;
}
24
Might assume the Process
argument is the target process.
You’d be wrong of course!
It’s the calling process.
James Forshaw @tiraniddo
Fun Use Case
25
Sandboxed ProcessUnsandboxed Process
void InjectExecutableCode(DWORD dwPid, PBYTE pData, SIZE_T nSize) {
HANDLE hProcess = OpenProcess(dwPid,
PROCESS_VM_WRITE| PROCESS_VM_OPERATION);
LPVOID pMem = VirtualAllocEx(hProcess,
PAGE_EXECUTE_READWRITE, nSize);
WriteProcessMemory(hProcess, pMem, pData, nSize);
}
New Executable
Memory
VirtualAllocEx
Create With Dynamic
Code Mitigation
James Forshaw @tiraniddo
Binary Signature Policy
struct PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY {
union {
DWORD Flags;
struct {
DWORD MicrosoftSignedOnly : 1;
DWORD StoreSignedOnly : 1; // Win10 Only.
DWORD MitigationOptIn : 1; // Win10 Only.
DWORD ReservedFlags : 29;
};
};
};
PCMP_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON (1 << 44)
26
Category: Increase Exploit Cost, Reduce Reliability
Can only specify Microsoft Signed at Process Creation
James Forshaw @tiraniddo
Under the Hood
case ProcessSignaturePolicy:
if (policy.MicrosoftSignedOnly) {
process->SignatureLevel = 8;
process->SectionSignatureLevel = 8;
} else if (policy.StoreSignedOnly) {
process->SignatureLevel = 6;
process->SectionSignatureLevel = 6;
}
process->Flags2 |= 0x2000;
27
MitigationOptIn is used to set the Flags2 flag, which opts into Store Signing
checks if an image is loaded which requires code signing.
James Forshaw @tiraniddo
Fun Use Case
28
Unsigned
Sandboxed Process
Unsandboxed Process
void* InjectExecutableImage(DWORD dwPid, HANDLE hMap) {
LPVOID lpMap = NULL;
HANDLE hProcess = OpenProcess(dwPid,
PROCESS_VM_WRITE| PROCESS_VM_OPERATION);
NtMapViewOfSection(hMap, hProcess, &lpMap, 0,
4096, nullptr, &viewsize,
ViewUnmap, 0, PAGE_EXECUTE_READWRITE);
return lpMap;
}
New Executable
Image Section
NtMapViewOfSection
Create With Process
Mitigation
Signature check
NOT enforced on
main executable.
NtMapViewOfSection can
take a process handle
James Forshaw @tiraniddo
Image Load Policy (Win10 Only)
struct PROCESS_MITIGATION_IMAGE_LOAD_POLICY {
union {
DWORD Flags;
struct {
DWORD NoRemoteImages : 1;
DWORD NoLowMandatoryLabelImages : 1;
DWORD ReservedFlags : 30;
};
};
};
PCMP_IMAGE_LOAD_NO_REMOTE_ALWAYS_ON (1 << 52)
PCMP_IMAGE_LOAD_NO_LOW_LABEL_ALWAYS_ON (1 << 56)
29
Category: Increase Exploit Cost, Reduce Reliability
James Forshaw @tiraniddo
Under the Hood
NTSTATUS MiAllowImageMap(EPROCESS *process, SECTION*
section)
{
unsigned int flags3 = process->Flags3;
if (flags3 & PROCESS_FLAGS3_NOREMOTEIMAGE &&
(section->FileObject->RemoteImageFileObject ||
section->FileObject->RemoteDataFileObject))
return STATUS_ACCESS_DENIED;
if (flags3 & PROCESS_FLAGS3_NOLOWILIMAGE) {
DWORD il = 0;
SeQueryObjectMandatoryLabel(section->FileObject, &il);
if (il <= SECURITY_MANDATORY_LOW_RID)
return STATUS_ACCESS_DENIED;
}
return STATUS_SUCCESS;
}
30
James Forshaw @tiraniddo
Font Disable Policy (Win10 Only)
struct PROCESS_MITIGATION_FONT_DISABLE_POLICY {
union {
DWORD Flags;
struct {
DWORD DisableNonSystemFonts : 1;
DWORD AuditNonSystemFontLoading : 1;
DWORD ReservedFlags : 30;
};
};
};
PCMP_FONT_DISABLE_ALWAYS_ON (1 << 48)
PCMP_AUDIT_NONSYSTEM_FONTS (3 << 48)
31
Category: Reduced Attack Surface
James Forshaw @tiraniddo
Font Disable Auditing
32
James Forshaw @tiraniddo
Also Available in EMET 5.5
33
James Forshaw @tiraniddo
Under the Hood
● Win32k shouldn’t have insider knowledge of EPROCESS Flags
34
int GetCurrentProcessFontLoadingOption()
{
PROCESS_MITIGATION_FONT_DISABLE_POLICY policy;
ZwQueryInformationProcess((HANDLE)-1,
ProcessMitigationPolicy, &policy, sizeof(policy), 0);
if (policy.DisableNonSystemFonts)
return 2;
else
return policy.AuditNonSystemFontLoading;
}
James Forshaw @tiraniddo
How it Works
35
int WIN32K::bLoadFont(...) {
int load_option = GetCurrentProcessFontLoadingOption();
bool system_font = true;
if (load_option) {
HANDLE hFile = hGetHandleFromFilePath(FontPath);
BOOL system_font = bIsFileInSystemFontsDir(hFile);
ZwClose(hFile);
if (!system_font) {
LogFontLoadAttempt(FontPath);
if (load_option == 2)
return 0;
}
}
HANDLE hFont = hGetHandleFromFilePath(FontPath);
// Map font as section
}
James Forshaw @tiraniddo
Demo Time!
Bypass Font Path Check
36
James Forshaw @tiraniddo
Syscall Disable Policy
struct PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY {
union {
DWORD Flags;
struct {
DWORD DisallowWin32kSystemCalls : 1;
DWORD ReservedFlags : 31;
};
};
};
PCMP_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON (1 << 28)
37
Category: Reduced Attack Surface
James Forshaw @tiraniddo
Win32k Syscall Disable Implementation?
SyscallEnter() {
// Setup entry.
if (IsWin32kSyscall(SyscallNumber) &&
CurrentProcess->Flags2 & WIN32K_SYSCALL_DISABLE) {
return STATUS_ACCESS_DENIED;
}
// Continue normal system call dispatch.
}
38
James Forshaw @tiraniddo
Win32k Syscall Disable
SyscallEnter() {
SERVICE_TABLE* table =
KeGetCurrentThread()->ServiceTable;
// Setup entry.
if (IsWin32Syscall(SyscallNo) &&
SyscallNo & 0xFFF > table->Shadow.Length)
if (PsConvertToGuiThread() != STATUS_SUCCESS)
return GetWin32kResult(SyscallNo);
}
// Continue normal system call dispatch.
}
39
James Forshaw @tiraniddo
Win32k Syscall Disable is Per Thread
NTSTATUS PsConvertToGuiThread() {
KTHREAD *thread = KeGetCurrentThread();
EPROCESS *process = thread->Process;
if (thread->ServiceTable != &KeServiceDescriptorTable)
return STATUS_ALREADY_WIN32;
if (process->Flags2 & WIN32K_SYSCALL_DISABLE)
return STATUS_ACCESS_DENIED;
thread->ServiceTable = &KeServiceDescriptorTableShadow;
NTSTATUS result = PsInvokeWin32Callout(THREAD_INIT,
&thread);
if (result < 0)
thread->ServiceTable = &KeServiceDescriptorTable;
return result;
}
40
James Forshaw @tiraniddo
Late Enable Initial Thread Problem
41
Sandboxed Process
Ntdll.dll
LdrxCallInitRoutine
Load
user32.dll
UserClientDllInitialize()
gdi32.dll
GdiDllInitialize()
combase.dll
ComBaseInitialize()
Kernel/Win32k
Initial Thread now a GUI Thread!
James Forshaw @tiraniddo
Disable Dynamically
case ProcessSystemCallDisablePolicy:
PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY policy;
if (!policy.DisallowWin32kSystemCalls
&& process->Flags2 & WIN32K_SYSCALL_DISABLE) {
return STATUS_ACCESS_DENIED;
}
process->Flags2 |= WIN32K_SYSCALL_DISABLE;
if (thread->ServiceTable != &KeServiceDescriptorTable) {
return STATUS_TOO_LATE;
}
42
We are too late for this thread, but it’
ll still enable the mitigation for the
process
James Forshaw @tiraniddo
Set at Process Creation
43
Sandboxed Process
Ntdll.dll
LdrxCallInitRoutine
Load
user32.dll
UserClientDllInitialize()
gdi32.dll
GdiDllInitialize()
combase.dll
ComBaseInitialize()
Kernel/Win32k
James Forshaw @tiraniddo
Set at Process Creation
44
Sandboxed Process
Ntdll.dll
LdrxCallInitRoutine
Load
user32.dll
UserClientDllInitialize()
gdi32.dll
GdiDllInitialize()
combase.dll
ComBaseInitialize()
Kernel/Win32k
James Forshaw @tiraniddo
How Does Chrome Do It?
● Chrome hooks the NtMapViewOfSection system call in NTDLL.
● Patches GdiDllInitialize before anything has a chance to call it.
45
BOOL WINAPI TargetGdiDllInitialize (
GdiDllInitializeFunction orig_gdi_dll_initialize ,
HANDLE dll ,
DWORD reason ) {
return TRUE;
}
HGDIOBJ WINAPI TargetGetStockObject (
GetStockObjectFunction orig_get_stock_object ,
int object) {
return reinterpret_cast <HGDIOBJ>(NULL);
}
ATOM WINAPI TargetRegisterClassW (
RegisterClassWFunction orig_register_class_function ,
const WNDCLASS* wnd_class) {
return TRUE;
}
James Forshaw @tiraniddo
Syscall Return Values
46
Expect NULL on error
Really NtGdiCreateCompatibleDC System Call
Expect a valid HDC on success
Really NtUserGetDC System Call
James Forshaw @tiraniddo
Let’s Test
47
Erm? 0xC000001C neither valid HDC or NULL
GetDC Looks okay
James Forshaw @tiraniddo
Handling Return Code
INT32 GetWin32kResult(DWORD SyscallNo) {
if (SyscallNo & 0xFFF < ShadowTableLength) {
INT8* ReturnCodes =
(INT8*)&ShadowTable[ShadowTableLength];
INT32 Result = ReturnCodes[SyscallNo & 0xFFF];
if (Result <= 0)
return Result;
}
return STATUS_INVALID_SYSTEM_SERVICE;
}
48
Just happens to equal 0xC000001C,
returned if Result > 0
Return code map at end of shadow table
Pass through value is <= 0
James Forshaw @tiraniddo
● No policies can be disabled once set in-process.
● However only a small subset of mitigations are inherited
● See PspApplyMitigationOptions.
● we need to block new process creation.
Process Mitigations Inheritance
49
Policy Inherited
Dynamic Code No
System Call Disable Yes
Signature No
Font Disable No
Image Load Yes
James Forshaw @tiraniddo
Job Objects to the Rescue
50
1 Active Process
No Breakout Allowed
Can’t create new process
James Forshaw @tiraniddo
Job Object
The Trouble with Job Objects
51
WMI Service
Win32_Process::Create
User Process
Console Driver
AllocConsole
Kernel
James Forshaw @tiraniddo
Job Object
The Trouble with Job Objects
52
WMI Service
Win32_Process::Create
User Process
Console Driver
AllocConsole
Kernel
notepad.exe
James Forshaw @tiraniddo
Job Object
The Trouble with Job Objects
53
WMI Service
Win32_Process::Create
User Process
Console Driver
AllocConsole
Kernel
conhost.exe
https://bugs.chromium.org/p/project-zero/issues/detail?id=213
Kernel can specify to breako
of job object, normally
required TCB privilege.
James Forshaw @tiraniddo
Job Object
The Trouble with Job Objects
54
WMI Service
Win32_Process::Create
User Process
Console Driver
AllocConsole
Kernel
conhost.exe
notepad.exe
Open Process and Inject Code
James Forshaw @tiraniddo
New Process Attribute for Win10 TH2
const int ProcThreadAttributeChildProcessPolicy = 14;
//
// Define Attribute to disable creation of child process
//
#define PROCESS_CREATION_CHILD_PROCESS_RESTRICTED 0x01
#define PROCESS_CREATION_CHILD_PROCESS_OVERRIDE 0x02
#define PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY 
ProcThreadAttributeValue(
ProcThreadAttributeChildProcessPolicy,
FALSE, TRUE, FALSE)
55
James Forshaw @tiraniddo
Pretty Effective Mitigation
56
WMI Service
Win32_Process::Create
User Process
Console Driver
AllocConsole
Kernel
conhost.exe
notepad.exe
PROCESS_CREATION_RESTRICTED
James Forshaw @tiraniddo
Inside SeSubProcessToken
DWORD ChildProcessPolicyFlag = // From process attribute.
BOOLEAN ChildProcessAllowed = TokenObject->TokenFlags &
CHILD_PROCESS_RESTRICTED;
if (!ChildProcessAllowed) {
if (!(ChildProcessPolicyFlag &
PROCESS_CREATION_CHILD_PROCESS_OVERRIDE)
|| !SeSinglePrivilegeCheck(SeTcbPrivilege))
return STATUS_ACCESS_DENIED;
}
SepDuplicateToken(TokenObject, ..., &NewTokenObject);
if (ChildProcessPolicyFlag &
PROCESS_CREATION_CHILD_PROCESS_RESTRICTED)
NewTokenObject->TokenFlags |= CHILD_PROCESS_RESTRICTED;
57
Mitigation is on Token not Process
James Forshaw @tiraniddo
Low Box Tokens (AppContainers)
● Many specific checks in the kernel for lowbox tokens
○ No NULL DACL access
○ Limited access to ATOM tables
● Capabilities which prevent access to things like network stack
● No read-up by default
● COM marshaling mitigations
○ Marshaled objects from AppContainers are untrusted
● Driver Traversal Check
○ Undocumented
FILE_DEVICE_ALLOW_APPCONTAINER_TRAVERSAL device
characteristic
58
James Forshaw @tiraniddo
Implicit Mitigations
59
James Forshaw @tiraniddo
ExIsRestrictedCaller
● Kernel function introduced in Windows 8.1
● Indicates whether the caller is “restricted”, what this actually means
in practice is whether the caller has an IL < Medium or is a Low Box
Token
● Only used to filter out sensitive kernel addresses to limit KASLR
leaks
○ Blocks profiling kernel addresses
○ Limits access to handle list which contains object addresses
○ Limits access to object type information
○ Limits thread and process information which leaks kernel addresses
● More information on Alex Ionescu’s blog:
○ http://www.alex-ionescu.com/?p=82
60
James Forshaw @tiraniddo
RtlIsSandboxedToken
● Very similar function to ExIsRestrictedCaller, but passes an token
● Introduced in Windows 10 but backported to Windows 7
61
BOOLEAN RtlIsSandboxedToken(PSECURITY_SUBJECT_CONTEXT
SubjectSecurityContext) {
SECURITY_SUBJECT_CONTEXT SecurityContext;
if (!SubjectSecurityContext) {
SeCaptureSubjectContext(&SecurityContext);
SubjectSecurityContext = &SecurityContext;
}
return !SeAccessCheck(
SeMediumDaclSd,
SubjectSecurityContext,
0x20000u);
}
James Forshaw @tiraniddo
Blocking Object Manager Symbolic Links
62
Sandboxed ProcessUnsandboxed Process
Symbolic Link
Object
NTSTATUS NtCreateSymbolicLinkObject(...) {
// ...
OBJECT_SYMBOLIC_LINK Object;
// Setup object.
Object->Flags = RtlIsSandboxedToken(NULL)
? 2 : 0;
}
James Forshaw @tiraniddo
Blocking Object Manager Symbolic Links
63
Sandboxed ProcessUnsandboxed Process
Symbolic Link
Object
NTSTATUS ObpParseSymbolicLink(...) {
// ...
if (Object->Flags & 2
&& !RtlIsSandboxedToken(NULL))
return STATUS_OBJECT_NAME_NOT_FOUND;
}
James Forshaw @tiraniddo
Blocking Registry Key Symbolic Links
NTSTATUS CmpCheckCreateAccess(...) {
BOOLEAN AccessGranted = SeAccessCheck(...);
if (AccessGranted &&
CreateOptions & REG_OPTION_CREATE_LINK &&
RtlIsSandboxedToken()) {
return STATUS_ACCESS_DENIED;
}
}
64
NTSTATUS CmSetValueKey(...) {
if(Type == REG_LINK &&
RtlEqualUnicodeString(&CmSymbolicLinkValueName,
ValueName, TRUE) &&
RtlIsSandboxedToken())
return STATUS_ACCESS_DENIED;
}
James Forshaw @tiraniddo
Blocking NTFS Mount Points
NTSTATUS IopXxxControlFile(...) {
if (ControlCode == FSCTL_SET_REPARSE_POINT &&
RtlIsSandboxedToken()) {
status = FsRtlValidateReparsePointBuffer(buffer);
if (status < 0)
return status;
if (buffer.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
InitializeObjectAttributes(&ObjAttr,
reparse_buffer.PathBuffer, ...);
status = ZwOpenFile(&FileHandle, FILE_GENERIC_WRITE,
&ObjAttr, ..., FILE_DIRECTORY_FILE);
if (status < 0)
return status;
// Continue.
}
}
}
65
Checks target is a directory and
writable
James Forshaw @tiraniddo
TOCTOU Setting Mount Point
66
Sandboxed ProcessUnsandboxed Process
Mount Point
Non-Writable
Directory
Writable
Directory
Set Mount Point
James Forshaw @tiraniddo
TOCTOU Setting Mount Point
67
Sandboxed ProcessUnsandboxed Process
Mount Point
Non-Writable
Directory
Writable
Directory
Same Path,
Different Target.
James Forshaw @tiraniddo
TOCTOU Setting Mount Point
68
Sandboxed ProcessUnsandboxed Process
Mount Point
Non-Writable
Directory
Writable
Directory
Write me a file!
James Forshaw @tiraniddo
Blocking NTFS Mount Points
69
?? C: windows
Per-User DeviceHarddiskVolume1 windows
Device Map Directory Drive Letter Symbolic Link Volume Path
James Forshaw @tiraniddo
Blocking NTFS Mount Points
70
?? C: windows
Per-User DeviceHarddiskVolume1 windows
Device Map Directory Drive Letter Symbolic Link Volume Path
James Forshaw @tiraniddo
Per-Process Device Map
71
const int ProcessDeviceMap = 23;
struct PROCESS_DEVICEMAP_INFORMATION {
HANDLE DirectoryHandle;
};
bool SetProcessDeviceMap(HANDLE hDir) {
PROCESS_DEVICEMAP_INFORMATION DeviceMap = {hDir};
NTSTATUS status = NtSetInformationProcess(
GetCurrentProcess(),
ProcessDeviceMap,
&DeviceMap,
sizeof(DeviceMap));
return status == 0;
}
James Forshaw @tiraniddo
Blocking NTFS Mount Points
72
?? C: windows
Per-Process Object Directory C: Symlink windows
Device Map Directory Fake Drive Letter Symbolic
Link
Fake Volume
Path
Writable Directory
James Forshaw @tiraniddo
Blocking Process Device Map
NTSTATUS NtSetInformationProcess(...) {
// ...
case ProcessDeviceMap:
HANDLE hDir = *(HANDLE*)Data;
if (RtlIsSandboxedToken())
return STATUS_ACCESS_DENIED;
return ObSetDeviceMap(ProcessObject, hDir);
// ...
}
73
https://bugs.chromium.org/p/project-zero/issues/detail?id=486
James Forshaw @tiraniddo
Bypass Using Anonymous Token
74
?? C: windows
Anonymous User Object Directory C: Symlink windows
Device Map Directory Fake Drive Letter Symbolic
Link
Fake Volume
Path
Writable Directory
Call ImpersonateAnonymousToken()
https://bugs.chromium.org/p/project-zero/issues/detail?id=573
https://bugs.chromium.org/p/project-zero/issues/detail?id=589
James Forshaw @tiraniddo
NTFS Hard Links
75
James Forshaw @tiraniddo
Never Give a Vendor a Preview of your Slides
76
Hey Microsoft,
want to check my
44con slides?
James Forshaw @tiraniddo
Never Give a Vendor a Preview of your Slides
77
Please redact
the hardlink
slides. We’ll
fix it.
James Forshaw @tiraniddo
Never Give a Vendor a Preview of your Slides
78
Oh :( We’ll you
have 90 days...
James Forshaw @tiraniddo
Blocking NTFS Hardlinks
NTSTATUS NtSetInformationFile(...) {
case FileLinkInformation:
ACCESS_MASK RequiredAccess = 0;
if(RtlIsSandboxedToken()) {
RequiredAccess |= FILE_WRITE_ATTRIBUTES;
}
ObReferenceObjectByHandle(FileHandle, RequiredAccess);
}
79
Default, no access requires
In sandbox needs write
access
https://bugs.chromium.org/p/project-zero/issues/detail?id=531
James Forshaw @tiraniddo
The Ultimate Set of Options for Win10
● At least run with a lowbox token, ideally lowbox+restricted
○ Kicks in implicit sandbox mitigations
● Disable dynamic code
● Only allow Microsoft signed images to be loaded
● Disable child process creation
● Win32k Lockdown or at least block custom fonts
● Prevent loading DLLs from untrusted locations
80
James Forshaw @tiraniddo
Wrapping Up
81
James Forshaw @tiraniddo
Conclusions
● Microsoft adding more and more sandbox related mitigations to the
core of Windows. Still a lot more could be done though.
● They’re actively fixing issues with the mitigations, something they’
ve never really done before.
● You can make a fairly secure sandbox, especially with attack
surface reduction.
82
James Forshaw @tiraniddo
References and Source Code
● Sandbox Analysis Tools
○ https://github.com/google/sandbox-attacksurface-analysis-tools
● Symbolic Link Testing Tools
○ https://github.com/google/symboliclink-testing-tools
● Chrome Windows Sandbox Code
○ https://code.google.
com/p/chromium/codesearch#chromium/src/sandbox/win/src/
83
James Forshaw @tiraniddo
Questions?
84

More Related Content

What's hot

(Ab)Using GPOs for Active Directory Pwnage
(Ab)Using GPOs for Active Directory Pwnage(Ab)Using GPOs for Active Directory Pwnage
(Ab)Using GPOs for Active Directory PwnagePetros Koutroumpis
 
8.8 Las Vegas - Adversary Emulation con C2 Matrix
8.8 Las Vegas - Adversary Emulation con C2 Matrix8.8 Las Vegas - Adversary Emulation con C2 Matrix
8.8 Las Vegas - Adversary Emulation con C2 MatrixJorge Orchilles
 
Understanding Windows Access Token Manipulation
Understanding Windows Access Token ManipulationUnderstanding Windows Access Token Manipulation
Understanding Windows Access Token ManipulationJustin Bui
 
Adversary Emulation Workshop
Adversary Emulation WorkshopAdversary Emulation Workshop
Adversary Emulation Workshopprithaaash
 
Privilege escalation from 1 to 0 Workshop
Privilege escalation from 1 to 0 Workshop Privilege escalation from 1 to 0 Workshop
Privilege escalation from 1 to 0 Workshop Hossam .M Hamed
 
Bypass_AV-EDR.pdf
Bypass_AV-EDR.pdfBypass_AV-EDR.pdf
Bypass_AV-EDR.pdfFarouk2nd
 
Effective Threat Hunting with Tactical Threat Intelligence
Effective Threat Hunting with Tactical Threat IntelligenceEffective Threat Hunting with Tactical Threat Intelligence
Effective Threat Hunting with Tactical Threat IntelligenceDhruv Majumdar
 
Threat-Based Adversary Emulation with MITRE ATT&CK
Threat-Based Adversary Emulation with MITRE ATT&CKThreat-Based Adversary Emulation with MITRE ATT&CK
Threat-Based Adversary Emulation with MITRE ATT&CKKatie Nickels
 
BSidesLV 2016 - Powershell - Hunting on the Endpoint - Gerritz
BSidesLV 2016 - Powershell - Hunting on the Endpoint - GerritzBSidesLV 2016 - Powershell - Hunting on the Endpoint - Gerritz
BSidesLV 2016 - Powershell - Hunting on the Endpoint - GerritzChristopher Gerritz
 
HITCON GIRLS_惡意程式分析介紹_in 成功大學_by Turkey_2016.04.28
HITCON GIRLS_惡意程式分析介紹_in 成功大學_by Turkey_2016.04.28HITCON GIRLS_惡意程式分析介紹_in 成功大學_by Turkey_2016.04.28
HITCON GIRLS_惡意程式分析介紹_in 成功大學_by Turkey_2016.04.28Shang Wei Li
 
LTEC 2013 - EnCase v7.08.01 presentation
LTEC 2013 - EnCase v7.08.01 presentation LTEC 2013 - EnCase v7.08.01 presentation
LTEC 2013 - EnCase v7.08.01 presentation Damir Delija
 
Pwning the Enterprise With PowerShell
Pwning the Enterprise With PowerShellPwning the Enterprise With PowerShell
Pwning the Enterprise With PowerShellBeau Bullock
 
(SEC306) Defending Against DDoS Attacks
(SEC306) Defending Against DDoS Attacks(SEC306) Defending Against DDoS Attacks
(SEC306) Defending Against DDoS AttacksAmazon Web Services
 
ROP 輕鬆談
ROP 輕鬆談ROP 輕鬆談
ROP 輕鬆談hackstuff
 
[CB19] Autopsyで迅速なマルウェアのスキャンとディスク内の簡単調査 by ターナー・功
[CB19] Autopsyで迅速なマルウェアのスキャンとディスク内の簡単調査 by ターナー・功[CB19] Autopsyで迅速なマルウェアのスキャンとディスク内の簡単調査 by ターナー・功
[CB19] Autopsyで迅速なマルウェアのスキャンとディスク内の簡単調査 by ターナー・功CODE BLUE
 
Malware analysis, threat intelligence and reverse engineering
Malware analysis, threat intelligence and reverse engineeringMalware analysis, threat intelligence and reverse engineering
Malware analysis, threat intelligence and reverse engineeringbartblaze
 

What's hot (20)

(Ab)Using GPOs for Active Directory Pwnage
(Ab)Using GPOs for Active Directory Pwnage(Ab)Using GPOs for Active Directory Pwnage
(Ab)Using GPOs for Active Directory Pwnage
 
8.8 Las Vegas - Adversary Emulation con C2 Matrix
8.8 Las Vegas - Adversary Emulation con C2 Matrix8.8 Las Vegas - Adversary Emulation con C2 Matrix
8.8 Las Vegas - Adversary Emulation con C2 Matrix
 
A Threat Hunter Himself
A Threat Hunter HimselfA Threat Hunter Himself
A Threat Hunter Himself
 
Understanding Windows Access Token Manipulation
Understanding Windows Access Token ManipulationUnderstanding Windows Access Token Manipulation
Understanding Windows Access Token Manipulation
 
Adversary Emulation Workshop
Adversary Emulation WorkshopAdversary Emulation Workshop
Adversary Emulation Workshop
 
Privilege escalation from 1 to 0 Workshop
Privilege escalation from 1 to 0 Workshop Privilege escalation from 1 to 0 Workshop
Privilege escalation from 1 to 0 Workshop
 
Bypass_AV-EDR.pdf
Bypass_AV-EDR.pdfBypass_AV-EDR.pdf
Bypass_AV-EDR.pdf
 
Effective Threat Hunting with Tactical Threat Intelligence
Effective Threat Hunting with Tactical Threat IntelligenceEffective Threat Hunting with Tactical Threat Intelligence
Effective Threat Hunting with Tactical Threat Intelligence
 
Windowsforensics
WindowsforensicsWindowsforensics
Windowsforensics
 
Stack pivot
Stack pivotStack pivot
Stack pivot
 
Threat-Based Adversary Emulation with MITRE ATT&CK
Threat-Based Adversary Emulation with MITRE ATT&CKThreat-Based Adversary Emulation with MITRE ATT&CK
Threat-Based Adversary Emulation with MITRE ATT&CK
 
BSidesLV 2016 - Powershell - Hunting on the Endpoint - Gerritz
BSidesLV 2016 - Powershell - Hunting on the Endpoint - GerritzBSidesLV 2016 - Powershell - Hunting on the Endpoint - Gerritz
BSidesLV 2016 - Powershell - Hunting on the Endpoint - Gerritz
 
HITCON GIRLS_惡意程式分析介紹_in 成功大學_by Turkey_2016.04.28
HITCON GIRLS_惡意程式分析介紹_in 成功大學_by Turkey_2016.04.28HITCON GIRLS_惡意程式分析介紹_in 成功大學_by Turkey_2016.04.28
HITCON GIRLS_惡意程式分析介紹_in 成功大學_by Turkey_2016.04.28
 
LTEC 2013 - EnCase v7.08.01 presentation
LTEC 2013 - EnCase v7.08.01 presentation LTEC 2013 - EnCase v7.08.01 presentation
LTEC 2013 - EnCase v7.08.01 presentation
 
Pwning the Enterprise With PowerShell
Pwning the Enterprise With PowerShellPwning the Enterprise With PowerShell
Pwning the Enterprise With PowerShell
 
(SEC306) Defending Against DDoS Attacks
(SEC306) Defending Against DDoS Attacks(SEC306) Defending Against DDoS Attacks
(SEC306) Defending Against DDoS Attacks
 
ROP 輕鬆談
ROP 輕鬆談ROP 輕鬆談
ROP 輕鬆談
 
Threat Modeling Using STRIDE
Threat Modeling Using STRIDEThreat Modeling Using STRIDE
Threat Modeling Using STRIDE
 
[CB19] Autopsyで迅速なマルウェアのスキャンとディスク内の簡単調査 by ターナー・功
[CB19] Autopsyで迅速なマルウェアのスキャンとディスク内の簡単調査 by ターナー・功[CB19] Autopsyで迅速なマルウェアのスキャンとディスク内の簡単調査 by ターナー・功
[CB19] Autopsyで迅速なマルウェアのスキャンとディスク内の簡単調査 by ターナー・功
 
Malware analysis, threat intelligence and reverse engineering
Malware analysis, threat intelligence and reverse engineeringMalware analysis, threat intelligence and reverse engineering
Malware analysis, threat intelligence and reverse engineering
 

Similar to The Joy of Sandbox Mitigations

A Fast Intro to Fast Query with ClickHouse, by Robert Hodges
A Fast Intro to Fast Query with ClickHouse, by Robert HodgesA Fast Intro to Fast Query with ClickHouse, by Robert Hodges
A Fast Intro to Fast Query with ClickHouse, by Robert HodgesAltinity Ltd
 
Linux Security APIs and the Chromium Sandbox (SwedenCpp Meetup 2017)
Linux Security APIs and the Chromium Sandbox (SwedenCpp Meetup 2017)Linux Security APIs and the Chromium Sandbox (SwedenCpp Meetup 2017)
Linux Security APIs and the Chromium Sandbox (SwedenCpp Meetup 2017)Patricia Aas
 
Hack any website
Hack any websiteHack any website
Hack any websitesunil kumar
 
HKG18-TR14 - Postmortem Debugging with Coresight
HKG18-TR14 - Postmortem Debugging with CoresightHKG18-TR14 - Postmortem Debugging with Coresight
HKG18-TR14 - Postmortem Debugging with CoresightLinaro
 
Java Performance Mistakes
Java Performance MistakesJava Performance Mistakes
Java Performance MistakesAndreas Grabner
 
Embedded Recipes 2019 - RT is about to make it to mainline. Now what?
Embedded Recipes 2019 - RT is about to make it to mainline. Now what?Embedded Recipes 2019 - RT is about to make it to mainline. Now what?
Embedded Recipes 2019 - RT is about to make it to mainline. Now what?Anne Nicolas
 
Accelerated .NET Memory Dump Analysis training public slides
Accelerated .NET Memory Dump Analysis training public slidesAccelerated .NET Memory Dump Analysis training public slides
Accelerated .NET Memory Dump Analysis training public slidesDmitry Vostokov
 
Linux Security and How Web Browser Sandboxes Really Work (Security Researcher...
Linux Security and How Web Browser Sandboxes Really Work (Security Researcher...Linux Security and How Web Browser Sandboxes Really Work (Security Researcher...
Linux Security and How Web Browser Sandboxes Really Work (Security Researcher...Patricia Aas
 
Bypassing Windows Security Functions(en)
Bypassing Windows Security Functions(en)Bypassing Windows Security Functions(en)
Bypassing Windows Security Functions(en)abend_cve_9999_0001
 
BPF: Tracing and more
BPF: Tracing and moreBPF: Tracing and more
BPF: Tracing and moreBrendan Gregg
 
Sprint 131
Sprint 131Sprint 131
Sprint 131ManageIQ
 
P4 Introduction
P4 Introduction P4 Introduction
P4 Introduction Netronome
 
Linux Security and How Web Browser Sandboxes Really Work (NDC Oslo 2017)
Linux Security  and How Web Browser Sandboxes Really Work (NDC Oslo 2017)Linux Security  and How Web Browser Sandboxes Really Work (NDC Oslo 2017)
Linux Security and How Web Browser Sandboxes Really Work (NDC Oslo 2017)Patricia Aas
 
Your Peripheral Has Planted Malware—An Exploit of NXP SOCs Vulnerability
Your Peripheral Has Planted Malware—An Exploit of NXP SOCs VulnerabilityYour Peripheral Has Planted Malware—An Exploit of NXP SOCs Vulnerability
Your Peripheral Has Planted Malware—An Exploit of NXP SOCs VulnerabilityPriyanka Aash
 
Reversing & malware analysis training part 12 rootkit analysis
Reversing & malware analysis training part 12   rootkit analysisReversing & malware analysis training part 12   rootkit analysis
Reversing & malware analysis training part 12 rootkit analysisAbdulrahman Bassam
 
Troubleshooting .net core on linux
Troubleshooting .net core on linuxTroubleshooting .net core on linux
Troubleshooting .net core on linuxPavel Klimiankou
 
Under the hood of modern HIPS-es and Windows access control mechanisms
Under the hood of modern HIPS-es and Windows access control mechanismsUnder the hood of modern HIPS-es and Windows access control mechanisms
Under the hood of modern HIPS-es and Windows access control mechanismsReCrypt
 
Double agent zero-day code injection and persistence technique
Double agent  zero-day code injection and persistence techniqueDouble agent  zero-day code injection and persistence technique
Double agent zero-day code injection and persistence techniqueKarlFrank99
 

Similar to The Joy of Sandbox Mitigations (20)

A Fast Intro to Fast Query with ClickHouse, by Robert Hodges
A Fast Intro to Fast Query with ClickHouse, by Robert HodgesA Fast Intro to Fast Query with ClickHouse, by Robert Hodges
A Fast Intro to Fast Query with ClickHouse, by Robert Hodges
 
Linux Security APIs and the Chromium Sandbox (SwedenCpp Meetup 2017)
Linux Security APIs and the Chromium Sandbox (SwedenCpp Meetup 2017)Linux Security APIs and the Chromium Sandbox (SwedenCpp Meetup 2017)
Linux Security APIs and the Chromium Sandbox (SwedenCpp Meetup 2017)
 
Hack any website
Hack any websiteHack any website
Hack any website
 
HKG18-TR14 - Postmortem Debugging with Coresight
HKG18-TR14 - Postmortem Debugging with CoresightHKG18-TR14 - Postmortem Debugging with Coresight
HKG18-TR14 - Postmortem Debugging with Coresight
 
Java Performance Mistakes
Java Performance MistakesJava Performance Mistakes
Java Performance Mistakes
 
Embedded Recipes 2019 - RT is about to make it to mainline. Now what?
Embedded Recipes 2019 - RT is about to make it to mainline. Now what?Embedded Recipes 2019 - RT is about to make it to mainline. Now what?
Embedded Recipes 2019 - RT is about to make it to mainline. Now what?
 
Accelerated .NET Memory Dump Analysis training public slides
Accelerated .NET Memory Dump Analysis training public slidesAccelerated .NET Memory Dump Analysis training public slides
Accelerated .NET Memory Dump Analysis training public slides
 
D3 Troubleshooting
D3 TroubleshootingD3 Troubleshooting
D3 Troubleshooting
 
Linux Security and How Web Browser Sandboxes Really Work (Security Researcher...
Linux Security and How Web Browser Sandboxes Really Work (Security Researcher...Linux Security and How Web Browser Sandboxes Really Work (Security Researcher...
Linux Security and How Web Browser Sandboxes Really Work (Security Researcher...
 
Bypassing Windows Security Functions(en)
Bypassing Windows Security Functions(en)Bypassing Windows Security Functions(en)
Bypassing Windows Security Functions(en)
 
BPF: Tracing and more
BPF: Tracing and moreBPF: Tracing and more
BPF: Tracing and more
 
Twitter Fabric
Twitter FabricTwitter Fabric
Twitter Fabric
 
Sprint 131
Sprint 131Sprint 131
Sprint 131
 
P4 Introduction
P4 Introduction P4 Introduction
P4 Introduction
 
Linux Security and How Web Browser Sandboxes Really Work (NDC Oslo 2017)
Linux Security  and How Web Browser Sandboxes Really Work (NDC Oslo 2017)Linux Security  and How Web Browser Sandboxes Really Work (NDC Oslo 2017)
Linux Security and How Web Browser Sandboxes Really Work (NDC Oslo 2017)
 
Your Peripheral Has Planted Malware—An Exploit of NXP SOCs Vulnerability
Your Peripheral Has Planted Malware—An Exploit of NXP SOCs VulnerabilityYour Peripheral Has Planted Malware—An Exploit of NXP SOCs Vulnerability
Your Peripheral Has Planted Malware—An Exploit of NXP SOCs Vulnerability
 
Reversing & malware analysis training part 12 rootkit analysis
Reversing & malware analysis training part 12   rootkit analysisReversing & malware analysis training part 12   rootkit analysis
Reversing & malware analysis training part 12 rootkit analysis
 
Troubleshooting .net core on linux
Troubleshooting .net core on linuxTroubleshooting .net core on linux
Troubleshooting .net core on linux
 
Under the hood of modern HIPS-es and Windows access control mechanisms
Under the hood of modern HIPS-es and Windows access control mechanismsUnder the hood of modern HIPS-es and Windows access control mechanisms
Under the hood of modern HIPS-es and Windows access control mechanisms
 
Double agent zero-day code injection and persistence technique
Double agent  zero-day code injection and persistence techniqueDouble agent  zero-day code injection and persistence technique
Double agent zero-day code injection and persistence technique
 

Recently uploaded

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 

Recently uploaded (20)

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 

The Joy of Sandbox Mitigations

  • 1. The Joy of Sandbox Mitigations James Forshaw @tiraniddo Troopers 2016 1
  • 2. James Forshaw @tiraniddo What I’m Going to Talk About ● Sandbox related mitigations added to Windows since Windows 8 ● Hardcore reverse engineering of the implementation ● What’s supported and how you can use them yourself ● What is blocked if you’re investigating sandbox attack surface ● Weird bugs and edge cases with the implementation ● Research on Windows 8.1 and 10 build 10586 2
  • 3. James Forshaw @tiraniddo WARNING A huge amount of code snippets is approaching. Sorry? 3
  • 4. James Forshaw @tiraniddo In the Beginning was DEP 4
  • 5. James Forshaw @tiraniddo The External Attacker’s Viewpoint 5 Mitigations: DEP ASLR SafeSEH Stack Cookies Control Flow Guard (CFG) etc. System Services Kernel Services Device Drivers Prevent RCETarget Process
  • 6. James Forshaw @tiraniddo The Defender’s Dilemma Assume Compromise 6
  • 7. James Forshaw @tiraniddo Sandboxing to the Rescue? 7 Sandboxed Target Process User Applications System Services Kernel Services Device Drivers Prevent RCE PreventEoP
  • 8. James Forshaw @tiraniddo Technical Mitigations 8 Reduce Attack Surface Increase Exploit Cost Reduce Exploit Reliability
  • 9. James Forshaw @tiraniddo Technical Mitigations 9 Reduce Attack Surface Increase Exploit Cost Reduce Exploit Reliability $ $
  • 10. James Forshaw @tiraniddo Technical Mitigations 10 Reduce Attack Surface Increase Exploit Cost Reduce Exploit Reliability
  • 11. James Forshaw @tiraniddo Categories of Windows Sandbox Mitigations Implicit Mitigations ● On by default when running sandboxed code ● Applies to select features which shouldn’t affect typical backwards compatibility support ● Focus more on breaking chains and making exploitation harder 11 Explicit Mitigations ● Mitigations which must be actively enabled ● Usually more disruptive, requires changes to existing code to support ● Aim to reduce attack surface or increase exploitation costs
  • 13. James Forshaw @tiraniddo Setting an Explicit Mitigation Policy 13 Policy Type Accompanying Data
  • 14. James Forshaw @tiraniddo PROCESS_MITIGATION_POLICY 14 Policy Supported Win8.1 Update 2 Supported Win10 TH2 ProcessDEPPolicy Yes Yes ProcessASLRPolicy Yes Yes ProcessDynamicCodePolicy Yes Yes ProcessStrictHandleCheckPolicy Yes Yes ProcessSystemCallDisablePolicy Yes Yes ProcessMitigationOptionsMask Invalid Invalid ProcessExtensionPointDisablePolicy Yes Yes ProcessControlFlowGuardPolicy Invalid Invalid ProcessSignaturePolicy Yes* Yes ProcessFontDisablePolicy No Yes ProcessImageLoadPolicy No Yes * Not supported through SetProcessMitigationPolicy
  • 15. James Forshaw @tiraniddo PROCESS_MITIGATION_POLICY 15 Policy Supported Win8.1 Update 2 Supported Win10 TH2 ProcessDEPPolicy Yes Yes ProcessASLRPolicy Yes Yes ProcessDynamicCodePolicy Yes Yes ProcessStrictHandleCheckPolicy Yes Yes ProcessSystemCallDisablePolicy Yes Yes ProcessMitigationOptionsMask Invalid Invalid ProcessExtensionPointDisablePolicy Yes Yes ProcessControlFlowGuardPolicy Invalid Invalid ProcessSignaturePolicy Yes* Yes ProcessFontDisablePolicy No Yes ProcessImageLoadPolicy No Yes * Not supported through SetProcessMitigationPolicy
  • 16. James Forshaw @tiraniddo Under the Hood const int ProcessMitigationPolicy = 52; struct PROCESS_MITIGATION { PROCESS_MITIGATION_POLICY Policy; DWORD Flags; }; PROCESS_MITIGATION m = {ProcessSignaturePolicy, 1}; NtSetInformationProcess(GetCurrentProcess(), ProcessMitigationPolicy, &m, sizeof(m)); 16
  • 17. James Forshaw @tiraniddo Under the Hood const int ProcessMitigationPolicy = 52; struct PROCESS_MITIGATION { PROCESS_MITIGATION_POLICY Policy; DWORD Flags; }; PROCESS_MITIGATION m = {ProcessSignaturePolicy, 1}; NtSetInformationProcess(GetCurrentProcess(), ProcessMitigationPolicy, &m, sizeof(m)); 17 Can’t specify anything other than current process, it will fail.
  • 18. James Forshaw @tiraniddo Apply During Create Process LPPROC_THREAD_ATTRIBUTE_LIST attr_list = ... // Allocated InitializeProcThreadAttributeList(attr_list, 1, 0, &size); DWORD64 policy = PROCESS_CREATION_MITIGATION_POLICY_...; UpdateProcThreadAttribute(attr_list, 0, PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY, &policy, sizeof(policy), nullptr, nullptr); startInfo.StartupInfo.cb = sizeof(startInfo); startInfo.lpAttributeList = attr_list; // Create Process with EXTENDED_STARTUPINFO_PRESENT flag 18 I’ll abbreviate PROCESS_CREATION_MITIGATION_POLICY to PCMP otherwise it gets too long Process Attribute for Mitigation Policy
  • 19. James Forshaw @tiraniddo Image File Execution Options ● Specify REG_QWORD value MitigationOptions with same bit fields as used at process creation. 19 Registry Value Executable Name
  • 20. James Forshaw @tiraniddo Image File Execution Options Filter 20
  • 21. James Forshaw @tiraniddo Demo Time! Simple Mitigation Tests 21
  • 22. James Forshaw @tiraniddo Dynamic Code Policy struct PROCESS_MITIGATION_DYNAMIC_CODE_POLICY { union { DWORD Flags; struct { DWORD ProhibitDynamicCode : 1; DWORD ReservedFlags : 31; }; }; } PCMP_PROHIBIT_DYNAMIC_CODE_ALWAYS_ON (1 << 36) 22 Category: Increase Exploit Cost, Reduce Reliability
  • 23. James Forshaw @tiraniddo What Does it Disable? ● Calling VirtualAlloc with PAGE_EXECUTE_* ● MapViewOfFile with FILE_MAP_EXECUTE option ● Calling VirtualProtect with PAGE_EXECUTE_* etc. ● Reconfiguring the CFG bitmap via SetProcessValidCallTargets 23 It doesn’t disable loading DLLs/Image Sections!
  • 24. James Forshaw @tiraniddo Under the Hood NTSTATUS MiArbitraryCodeBlocked(EPROCESS *Process) { if (Process->Flags2 & DYNAMIC_CODE_BLOCKED_FLAG) return STATUS_DYNAMIC_CODE_BLOCKED; return STATUS_SUCCESS; } 24 Might assume the Process argument is the target process. You’d be wrong of course! It’s the calling process.
  • 25. James Forshaw @tiraniddo Fun Use Case 25 Sandboxed ProcessUnsandboxed Process void InjectExecutableCode(DWORD dwPid, PBYTE pData, SIZE_T nSize) { HANDLE hProcess = OpenProcess(dwPid, PROCESS_VM_WRITE| PROCESS_VM_OPERATION); LPVOID pMem = VirtualAllocEx(hProcess, PAGE_EXECUTE_READWRITE, nSize); WriteProcessMemory(hProcess, pMem, pData, nSize); } New Executable Memory VirtualAllocEx Create With Dynamic Code Mitigation
  • 26. James Forshaw @tiraniddo Binary Signature Policy struct PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY { union { DWORD Flags; struct { DWORD MicrosoftSignedOnly : 1; DWORD StoreSignedOnly : 1; // Win10 Only. DWORD MitigationOptIn : 1; // Win10 Only. DWORD ReservedFlags : 29; }; }; }; PCMP_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON (1 << 44) 26 Category: Increase Exploit Cost, Reduce Reliability Can only specify Microsoft Signed at Process Creation
  • 27. James Forshaw @tiraniddo Under the Hood case ProcessSignaturePolicy: if (policy.MicrosoftSignedOnly) { process->SignatureLevel = 8; process->SectionSignatureLevel = 8; } else if (policy.StoreSignedOnly) { process->SignatureLevel = 6; process->SectionSignatureLevel = 6; } process->Flags2 |= 0x2000; 27 MitigationOptIn is used to set the Flags2 flag, which opts into Store Signing checks if an image is loaded which requires code signing.
  • 28. James Forshaw @tiraniddo Fun Use Case 28 Unsigned Sandboxed Process Unsandboxed Process void* InjectExecutableImage(DWORD dwPid, HANDLE hMap) { LPVOID lpMap = NULL; HANDLE hProcess = OpenProcess(dwPid, PROCESS_VM_WRITE| PROCESS_VM_OPERATION); NtMapViewOfSection(hMap, hProcess, &lpMap, 0, 4096, nullptr, &viewsize, ViewUnmap, 0, PAGE_EXECUTE_READWRITE); return lpMap; } New Executable Image Section NtMapViewOfSection Create With Process Mitigation Signature check NOT enforced on main executable. NtMapViewOfSection can take a process handle
  • 29. James Forshaw @tiraniddo Image Load Policy (Win10 Only) struct PROCESS_MITIGATION_IMAGE_LOAD_POLICY { union { DWORD Flags; struct { DWORD NoRemoteImages : 1; DWORD NoLowMandatoryLabelImages : 1; DWORD ReservedFlags : 30; }; }; }; PCMP_IMAGE_LOAD_NO_REMOTE_ALWAYS_ON (1 << 52) PCMP_IMAGE_LOAD_NO_LOW_LABEL_ALWAYS_ON (1 << 56) 29 Category: Increase Exploit Cost, Reduce Reliability
  • 30. James Forshaw @tiraniddo Under the Hood NTSTATUS MiAllowImageMap(EPROCESS *process, SECTION* section) { unsigned int flags3 = process->Flags3; if (flags3 & PROCESS_FLAGS3_NOREMOTEIMAGE && (section->FileObject->RemoteImageFileObject || section->FileObject->RemoteDataFileObject)) return STATUS_ACCESS_DENIED; if (flags3 & PROCESS_FLAGS3_NOLOWILIMAGE) { DWORD il = 0; SeQueryObjectMandatoryLabel(section->FileObject, &il); if (il <= SECURITY_MANDATORY_LOW_RID) return STATUS_ACCESS_DENIED; } return STATUS_SUCCESS; } 30
  • 31. James Forshaw @tiraniddo Font Disable Policy (Win10 Only) struct PROCESS_MITIGATION_FONT_DISABLE_POLICY { union { DWORD Flags; struct { DWORD DisableNonSystemFonts : 1; DWORD AuditNonSystemFontLoading : 1; DWORD ReservedFlags : 30; }; }; }; PCMP_FONT_DISABLE_ALWAYS_ON (1 << 48) PCMP_AUDIT_NONSYSTEM_FONTS (3 << 48) 31 Category: Reduced Attack Surface
  • 32. James Forshaw @tiraniddo Font Disable Auditing 32
  • 33. James Forshaw @tiraniddo Also Available in EMET 5.5 33
  • 34. James Forshaw @tiraniddo Under the Hood ● Win32k shouldn’t have insider knowledge of EPROCESS Flags 34 int GetCurrentProcessFontLoadingOption() { PROCESS_MITIGATION_FONT_DISABLE_POLICY policy; ZwQueryInformationProcess((HANDLE)-1, ProcessMitigationPolicy, &policy, sizeof(policy), 0); if (policy.DisableNonSystemFonts) return 2; else return policy.AuditNonSystemFontLoading; }
  • 35. James Forshaw @tiraniddo How it Works 35 int WIN32K::bLoadFont(...) { int load_option = GetCurrentProcessFontLoadingOption(); bool system_font = true; if (load_option) { HANDLE hFile = hGetHandleFromFilePath(FontPath); BOOL system_font = bIsFileInSystemFontsDir(hFile); ZwClose(hFile); if (!system_font) { LogFontLoadAttempt(FontPath); if (load_option == 2) return 0; } } HANDLE hFont = hGetHandleFromFilePath(FontPath); // Map font as section }
  • 36. James Forshaw @tiraniddo Demo Time! Bypass Font Path Check 36
  • 37. James Forshaw @tiraniddo Syscall Disable Policy struct PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY { union { DWORD Flags; struct { DWORD DisallowWin32kSystemCalls : 1; DWORD ReservedFlags : 31; }; }; }; PCMP_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON (1 << 28) 37 Category: Reduced Attack Surface
  • 38. James Forshaw @tiraniddo Win32k Syscall Disable Implementation? SyscallEnter() { // Setup entry. if (IsWin32kSyscall(SyscallNumber) && CurrentProcess->Flags2 & WIN32K_SYSCALL_DISABLE) { return STATUS_ACCESS_DENIED; } // Continue normal system call dispatch. } 38
  • 39. James Forshaw @tiraniddo Win32k Syscall Disable SyscallEnter() { SERVICE_TABLE* table = KeGetCurrentThread()->ServiceTable; // Setup entry. if (IsWin32Syscall(SyscallNo) && SyscallNo & 0xFFF > table->Shadow.Length) if (PsConvertToGuiThread() != STATUS_SUCCESS) return GetWin32kResult(SyscallNo); } // Continue normal system call dispatch. } 39
  • 40. James Forshaw @tiraniddo Win32k Syscall Disable is Per Thread NTSTATUS PsConvertToGuiThread() { KTHREAD *thread = KeGetCurrentThread(); EPROCESS *process = thread->Process; if (thread->ServiceTable != &KeServiceDescriptorTable) return STATUS_ALREADY_WIN32; if (process->Flags2 & WIN32K_SYSCALL_DISABLE) return STATUS_ACCESS_DENIED; thread->ServiceTable = &KeServiceDescriptorTableShadow; NTSTATUS result = PsInvokeWin32Callout(THREAD_INIT, &thread); if (result < 0) thread->ServiceTable = &KeServiceDescriptorTable; return result; } 40
  • 41. James Forshaw @tiraniddo Late Enable Initial Thread Problem 41 Sandboxed Process Ntdll.dll LdrxCallInitRoutine Load user32.dll UserClientDllInitialize() gdi32.dll GdiDllInitialize() combase.dll ComBaseInitialize() Kernel/Win32k Initial Thread now a GUI Thread!
  • 42. James Forshaw @tiraniddo Disable Dynamically case ProcessSystemCallDisablePolicy: PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY policy; if (!policy.DisallowWin32kSystemCalls && process->Flags2 & WIN32K_SYSCALL_DISABLE) { return STATUS_ACCESS_DENIED; } process->Flags2 |= WIN32K_SYSCALL_DISABLE; if (thread->ServiceTable != &KeServiceDescriptorTable) { return STATUS_TOO_LATE; } 42 We are too late for this thread, but it’ ll still enable the mitigation for the process
  • 43. James Forshaw @tiraniddo Set at Process Creation 43 Sandboxed Process Ntdll.dll LdrxCallInitRoutine Load user32.dll UserClientDllInitialize() gdi32.dll GdiDllInitialize() combase.dll ComBaseInitialize() Kernel/Win32k
  • 44. James Forshaw @tiraniddo Set at Process Creation 44 Sandboxed Process Ntdll.dll LdrxCallInitRoutine Load user32.dll UserClientDllInitialize() gdi32.dll GdiDllInitialize() combase.dll ComBaseInitialize() Kernel/Win32k
  • 45. James Forshaw @tiraniddo How Does Chrome Do It? ● Chrome hooks the NtMapViewOfSection system call in NTDLL. ● Patches GdiDllInitialize before anything has a chance to call it. 45 BOOL WINAPI TargetGdiDllInitialize ( GdiDllInitializeFunction orig_gdi_dll_initialize , HANDLE dll , DWORD reason ) { return TRUE; } HGDIOBJ WINAPI TargetGetStockObject ( GetStockObjectFunction orig_get_stock_object , int object) { return reinterpret_cast <HGDIOBJ>(NULL); } ATOM WINAPI TargetRegisterClassW ( RegisterClassWFunction orig_register_class_function , const WNDCLASS* wnd_class) { return TRUE; }
  • 46. James Forshaw @tiraniddo Syscall Return Values 46 Expect NULL on error Really NtGdiCreateCompatibleDC System Call Expect a valid HDC on success Really NtUserGetDC System Call
  • 47. James Forshaw @tiraniddo Let’s Test 47 Erm? 0xC000001C neither valid HDC or NULL GetDC Looks okay
  • 48. James Forshaw @tiraniddo Handling Return Code INT32 GetWin32kResult(DWORD SyscallNo) { if (SyscallNo & 0xFFF < ShadowTableLength) { INT8* ReturnCodes = (INT8*)&ShadowTable[ShadowTableLength]; INT32 Result = ReturnCodes[SyscallNo & 0xFFF]; if (Result <= 0) return Result; } return STATUS_INVALID_SYSTEM_SERVICE; } 48 Just happens to equal 0xC000001C, returned if Result > 0 Return code map at end of shadow table Pass through value is <= 0
  • 49. James Forshaw @tiraniddo ● No policies can be disabled once set in-process. ● However only a small subset of mitigations are inherited ● See PspApplyMitigationOptions. ● we need to block new process creation. Process Mitigations Inheritance 49 Policy Inherited Dynamic Code No System Call Disable Yes Signature No Font Disable No Image Load Yes
  • 50. James Forshaw @tiraniddo Job Objects to the Rescue 50 1 Active Process No Breakout Allowed Can’t create new process
  • 51. James Forshaw @tiraniddo Job Object The Trouble with Job Objects 51 WMI Service Win32_Process::Create User Process Console Driver AllocConsole Kernel
  • 52. James Forshaw @tiraniddo Job Object The Trouble with Job Objects 52 WMI Service Win32_Process::Create User Process Console Driver AllocConsole Kernel notepad.exe
  • 53. James Forshaw @tiraniddo Job Object The Trouble with Job Objects 53 WMI Service Win32_Process::Create User Process Console Driver AllocConsole Kernel conhost.exe https://bugs.chromium.org/p/project-zero/issues/detail?id=213 Kernel can specify to breako of job object, normally required TCB privilege.
  • 54. James Forshaw @tiraniddo Job Object The Trouble with Job Objects 54 WMI Service Win32_Process::Create User Process Console Driver AllocConsole Kernel conhost.exe notepad.exe Open Process and Inject Code
  • 55. James Forshaw @tiraniddo New Process Attribute for Win10 TH2 const int ProcThreadAttributeChildProcessPolicy = 14; // // Define Attribute to disable creation of child process // #define PROCESS_CREATION_CHILD_PROCESS_RESTRICTED 0x01 #define PROCESS_CREATION_CHILD_PROCESS_OVERRIDE 0x02 #define PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY ProcThreadAttributeValue( ProcThreadAttributeChildProcessPolicy, FALSE, TRUE, FALSE) 55
  • 56. James Forshaw @tiraniddo Pretty Effective Mitigation 56 WMI Service Win32_Process::Create User Process Console Driver AllocConsole Kernel conhost.exe notepad.exe PROCESS_CREATION_RESTRICTED
  • 57. James Forshaw @tiraniddo Inside SeSubProcessToken DWORD ChildProcessPolicyFlag = // From process attribute. BOOLEAN ChildProcessAllowed = TokenObject->TokenFlags & CHILD_PROCESS_RESTRICTED; if (!ChildProcessAllowed) { if (!(ChildProcessPolicyFlag & PROCESS_CREATION_CHILD_PROCESS_OVERRIDE) || !SeSinglePrivilegeCheck(SeTcbPrivilege)) return STATUS_ACCESS_DENIED; } SepDuplicateToken(TokenObject, ..., &NewTokenObject); if (ChildProcessPolicyFlag & PROCESS_CREATION_CHILD_PROCESS_RESTRICTED) NewTokenObject->TokenFlags |= CHILD_PROCESS_RESTRICTED; 57 Mitigation is on Token not Process
  • 58. James Forshaw @tiraniddo Low Box Tokens (AppContainers) ● Many specific checks in the kernel for lowbox tokens ○ No NULL DACL access ○ Limited access to ATOM tables ● Capabilities which prevent access to things like network stack ● No read-up by default ● COM marshaling mitigations ○ Marshaled objects from AppContainers are untrusted ● Driver Traversal Check ○ Undocumented FILE_DEVICE_ALLOW_APPCONTAINER_TRAVERSAL device characteristic 58
  • 60. James Forshaw @tiraniddo ExIsRestrictedCaller ● Kernel function introduced in Windows 8.1 ● Indicates whether the caller is “restricted”, what this actually means in practice is whether the caller has an IL < Medium or is a Low Box Token ● Only used to filter out sensitive kernel addresses to limit KASLR leaks ○ Blocks profiling kernel addresses ○ Limits access to handle list which contains object addresses ○ Limits access to object type information ○ Limits thread and process information which leaks kernel addresses ● More information on Alex Ionescu’s blog: ○ http://www.alex-ionescu.com/?p=82 60
  • 61. James Forshaw @tiraniddo RtlIsSandboxedToken ● Very similar function to ExIsRestrictedCaller, but passes an token ● Introduced in Windows 10 but backported to Windows 7 61 BOOLEAN RtlIsSandboxedToken(PSECURITY_SUBJECT_CONTEXT SubjectSecurityContext) { SECURITY_SUBJECT_CONTEXT SecurityContext; if (!SubjectSecurityContext) { SeCaptureSubjectContext(&SecurityContext); SubjectSecurityContext = &SecurityContext; } return !SeAccessCheck( SeMediumDaclSd, SubjectSecurityContext, 0x20000u); }
  • 62. James Forshaw @tiraniddo Blocking Object Manager Symbolic Links 62 Sandboxed ProcessUnsandboxed Process Symbolic Link Object NTSTATUS NtCreateSymbolicLinkObject(...) { // ... OBJECT_SYMBOLIC_LINK Object; // Setup object. Object->Flags = RtlIsSandboxedToken(NULL) ? 2 : 0; }
  • 63. James Forshaw @tiraniddo Blocking Object Manager Symbolic Links 63 Sandboxed ProcessUnsandboxed Process Symbolic Link Object NTSTATUS ObpParseSymbolicLink(...) { // ... if (Object->Flags & 2 && !RtlIsSandboxedToken(NULL)) return STATUS_OBJECT_NAME_NOT_FOUND; }
  • 64. James Forshaw @tiraniddo Blocking Registry Key Symbolic Links NTSTATUS CmpCheckCreateAccess(...) { BOOLEAN AccessGranted = SeAccessCheck(...); if (AccessGranted && CreateOptions & REG_OPTION_CREATE_LINK && RtlIsSandboxedToken()) { return STATUS_ACCESS_DENIED; } } 64 NTSTATUS CmSetValueKey(...) { if(Type == REG_LINK && RtlEqualUnicodeString(&CmSymbolicLinkValueName, ValueName, TRUE) && RtlIsSandboxedToken()) return STATUS_ACCESS_DENIED; }
  • 65. James Forshaw @tiraniddo Blocking NTFS Mount Points NTSTATUS IopXxxControlFile(...) { if (ControlCode == FSCTL_SET_REPARSE_POINT && RtlIsSandboxedToken()) { status = FsRtlValidateReparsePointBuffer(buffer); if (status < 0) return status; if (buffer.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) { InitializeObjectAttributes(&ObjAttr, reparse_buffer.PathBuffer, ...); status = ZwOpenFile(&FileHandle, FILE_GENERIC_WRITE, &ObjAttr, ..., FILE_DIRECTORY_FILE); if (status < 0) return status; // Continue. } } } 65 Checks target is a directory and writable
  • 66. James Forshaw @tiraniddo TOCTOU Setting Mount Point 66 Sandboxed ProcessUnsandboxed Process Mount Point Non-Writable Directory Writable Directory Set Mount Point
  • 67. James Forshaw @tiraniddo TOCTOU Setting Mount Point 67 Sandboxed ProcessUnsandboxed Process Mount Point Non-Writable Directory Writable Directory Same Path, Different Target.
  • 68. James Forshaw @tiraniddo TOCTOU Setting Mount Point 68 Sandboxed ProcessUnsandboxed Process Mount Point Non-Writable Directory Writable Directory Write me a file!
  • 69. James Forshaw @tiraniddo Blocking NTFS Mount Points 69 ?? C: windows Per-User DeviceHarddiskVolume1 windows Device Map Directory Drive Letter Symbolic Link Volume Path
  • 70. James Forshaw @tiraniddo Blocking NTFS Mount Points 70 ?? C: windows Per-User DeviceHarddiskVolume1 windows Device Map Directory Drive Letter Symbolic Link Volume Path
  • 71. James Forshaw @tiraniddo Per-Process Device Map 71 const int ProcessDeviceMap = 23; struct PROCESS_DEVICEMAP_INFORMATION { HANDLE DirectoryHandle; }; bool SetProcessDeviceMap(HANDLE hDir) { PROCESS_DEVICEMAP_INFORMATION DeviceMap = {hDir}; NTSTATUS status = NtSetInformationProcess( GetCurrentProcess(), ProcessDeviceMap, &DeviceMap, sizeof(DeviceMap)); return status == 0; }
  • 72. James Forshaw @tiraniddo Blocking NTFS Mount Points 72 ?? C: windows Per-Process Object Directory C: Symlink windows Device Map Directory Fake Drive Letter Symbolic Link Fake Volume Path Writable Directory
  • 73. James Forshaw @tiraniddo Blocking Process Device Map NTSTATUS NtSetInformationProcess(...) { // ... case ProcessDeviceMap: HANDLE hDir = *(HANDLE*)Data; if (RtlIsSandboxedToken()) return STATUS_ACCESS_DENIED; return ObSetDeviceMap(ProcessObject, hDir); // ... } 73 https://bugs.chromium.org/p/project-zero/issues/detail?id=486
  • 74. James Forshaw @tiraniddo Bypass Using Anonymous Token 74 ?? C: windows Anonymous User Object Directory C: Symlink windows Device Map Directory Fake Drive Letter Symbolic Link Fake Volume Path Writable Directory Call ImpersonateAnonymousToken() https://bugs.chromium.org/p/project-zero/issues/detail?id=573 https://bugs.chromium.org/p/project-zero/issues/detail?id=589
  • 76. James Forshaw @tiraniddo Never Give a Vendor a Preview of your Slides 76 Hey Microsoft, want to check my 44con slides?
  • 77. James Forshaw @tiraniddo Never Give a Vendor a Preview of your Slides 77 Please redact the hardlink slides. We’ll fix it.
  • 78. James Forshaw @tiraniddo Never Give a Vendor a Preview of your Slides 78 Oh :( We’ll you have 90 days...
  • 79. James Forshaw @tiraniddo Blocking NTFS Hardlinks NTSTATUS NtSetInformationFile(...) { case FileLinkInformation: ACCESS_MASK RequiredAccess = 0; if(RtlIsSandboxedToken()) { RequiredAccess |= FILE_WRITE_ATTRIBUTES; } ObReferenceObjectByHandle(FileHandle, RequiredAccess); } 79 Default, no access requires In sandbox needs write access https://bugs.chromium.org/p/project-zero/issues/detail?id=531
  • 80. James Forshaw @tiraniddo The Ultimate Set of Options for Win10 ● At least run with a lowbox token, ideally lowbox+restricted ○ Kicks in implicit sandbox mitigations ● Disable dynamic code ● Only allow Microsoft signed images to be loaded ● Disable child process creation ● Win32k Lockdown or at least block custom fonts ● Prevent loading DLLs from untrusted locations 80
  • 82. James Forshaw @tiraniddo Conclusions ● Microsoft adding more and more sandbox related mitigations to the core of Windows. Still a lot more could be done though. ● They’re actively fixing issues with the mitigations, something they’ ve never really done before. ● You can make a fairly secure sandbox, especially with attack surface reduction. 82
  • 83. James Forshaw @tiraniddo References and Source Code ● Sandbox Analysis Tools ○ https://github.com/google/sandbox-attacksurface-analysis-tools ● Symbolic Link Testing Tools ○ https://github.com/google/symboliclink-testing-tools ● Chrome Windows Sandbox Code ○ https://code.google. com/p/chromium/codesearch#chromium/src/sandbox/win/src/ 83