Patroklos Argyroudis, Dimitris Glynos Fargp, Dimitrisgat . - PUT.AS

Transcription

P ROTECTING THE C OREK ERNEL E XPLOITATION M ITIGATIONSPatroklos Argyroudis, Dimitris Glynos{argp, dimitris} at census-labs.comCensus, Inc.Black Hat EU 2011P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

O VERVIEWI MPORTANCE OF K ERNEL S ECURITYK ERNEL MEMORY CORRUPTIONVULNERABILITIESU SERLAND MEMORY CORRUPTIONMITIGATIONSK ERNEL EXPLOITATION MITIGATIONSB YPASSING K ERNEL P ROTECTIONSC ONCLUSIONP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

I MPORTANCE OF KERNEL SECURITYIOperating system kernels are an attractive target forattackersIIIIIILarge code basesCountless entry points (syscalls, IOCTLs, FS code,network, etc.)Complicated interactions between subsystemsExperience has shown that kernels on productionsystems are seldom upgradedSandbox-based security measures can easily besubverted via kernel vulnerabilitiesIs the requirement of local access relevant anymore?IWeb apps, devices (iPhone, Android), remote bugsP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

K ERNEL MEMORY CORRUPTIONVULNERABILITIESINULL pointer dereferencesIIIKernel stack overflowsIIIUsed for initialization, to signify default, returned onerror, etc.Problem for systems that split the virtual addressspace into two, kernel and process spacePer-process or per-LWP stacksKernel internal functions’ stacksMemory allocator overflowsIICorrupt adjacent objectsCorrupt metadataP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

B UGS THAT LEAD TO MEMORY CORRUPTIONSIInsufficient validation of user inputIIITraditional insufficient bounds checkingArbitrary memory corruptions (array indexes,reference counters)Signednessfunc(size t user size) {int size user size;if(size MAX SIZE) {/* do some operation with size considered safe */IInteger overflowsvmalloc(sizeof(struct kvm cpuid entry2) * cpuid nent);IRace conditionsIIValidation time vs use timeChangeable locked resourcesP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

U SERLAND MEMORY CORRUPTIONMITIGATIONSIStack canariesIIHeap canariesIIIGuard valueUsed to encode elements of important structuresHeap safe unlinkingIIProtect metadata stored on the stackMetadata sanitizationASLRIIIILocation of stack randomizedRandom base address for dynamic librariesRandom base address for executables (e.g. PIE)Location of heap randomized (e.g. brk ASLR)P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

U SERLAND MEMORY CORRUPTIONMITIGATIONSIIIMark pages as ry Access Control (MAC) – SELinux,grsecurity (RBAC), AppArmor (path-based)Process debugging protectionIIICompile-time fortificationIIIForbid users to debug (their own) processes that arenot launched by a debuggerContain application compromises-D FORTIFY SOURCE 2Variable reorderinggrsecurity/PaX is the seminal work and providesmuch moreP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

K ERNEL EXPLOITATION MITIGATIONSP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUXFocus on Linux 2.6.37I Stack overflow protectionI SLUB Red ZoneI Memory protectionI NULL page mappingsI Poison pointer valuesI Linux Kernel ModulesI grsecurity patchP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: S TACK O VERFLOW P ROTECTIONSSP-type protectionI CC STACKPROTECTOR optionI gcc -fstack-protectorI affects the compilation of both kernel and modulesI local variable re-orderingI canary protection only for functions with localcharacter arrays 8 bytesIIin a kernel image with 16604 functions only 378 wereprotected (about 2%)if the canary is overwritten the kernel panicsP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: C ANARIESIA per-CPU canary is generated at boot-timeboot init stack canary @ arch/x86/include/asm/stackprotector.h61 u64 canary;62 u64 tsc;73 get random bytes(&canary, sizeof(canary));74 tsc native read tsc();75 canary tsc (tsc 32UL);77 current stack canary canary;81 percpu write(stack canary.canary, canary);IEach Lightweight Process (LWP) receives its ownkernel stack canarydup task struct @ kernel/fork.c281 tsk stack canary get random int()get random int @ drivers/char/random.c1634 hash[0] current pid jiffies get cycles();1635 ret half md4 transform(hash, keyptr secret);P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: C ANARIESIGCC expects to find the canary at %gs:0x14proc916.818491.106Ifdinfo read @ fs/proc/base.cmov %gs:0x14, %edxmov %edx, -0x10(%ebp).mov -0x10(%ebp), %edxxor %gs:0x14, %edxjne proc fdinfo read 106 .call stack chk fail The canary is placed right after the local variables,thus “protecting” the saved base pointer, the savedinstruction pointer and the function parametersP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: S TACK O VERFLOW E XAMPLEKernel panic - not syncing: stack-protector:Kernel stack is corrupted in c10e1ebfPid: 9028, comm: canary-test Tainted: G D 2.6.37 #1Call Trace:[ c1347887 ] ? printk 0x18/0x21[ c1347761 ] panic 0x57/0x165[ c1026339 ] stack chk fail 0x19/0x30[ c10e1ebf ] ? proc fdinfo read 0x6f/0x70[ c10e1ebf ] proc fdinfo read 0x6f/0x70[ c10a377d ] ? rw verify area 0x5d/0x100[ c10a42d9 ] vfs read 0x99/0x140[ c10e1e50 ] ? proc fdinfo read 0x0/0x70[ c10a443d ] sys read 0x3d/0x70[ c1002b97 ] sysenter do call 0x12/0x26P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: SLUB R ED Z ONEIThe SLUB is a kernel slab allocatorIIIIIIIt allocates contiguous “slabs” of memory for objectstorageEach slab may contain one or more objectsObjects are grouped in “caches”Each cache organizes objects of the same typeNew objects quickly reclaim the space of recently“deleted” objectsA “Red Zone” is a word-sized canary of ’0xcc’ bytesplaced right after every object in a slabIIIIt helps in identifying memory corruption bugs inkernel code (i.e. it’s not a security mechanism)If a Red Zone is overwritten, debug info is printed,Red Zone is restored and kernel continues executionRequires slub debug FZ boot-time option andSLUB DEBUG config optionP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: S LAB O VERFLOW E XAMPLEBUG kmalloc-1024: Redzone -------------------------------INFO: 0xc7ac9018-0xc7ac9018. First byte 0x33 instead of 0xccINFO: Slab 0xc7fe5900 objects 15 used 10 fp 0xc7aca850 flags 0x400040c0INFO: Object 0xc7ac8c18 @offset 3096 fp 0x33333333Bytes b4 0xc7ac8c08: 00 00 00 00 00 00 00 00 cc cc cc cc 00 00 00 00Object 0xc7ac8c18: 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33.Redzone 0xc7ac9018: 33 cc cc ccPadding 0xc7ac901c: 00 00 00 00Pid: Pid: 8382, comm: cat Not tainted 2.6.37 #2Call Trace:[ c10a0e77 ] print trailer 0xe7/0x130[ c10a152d ] check bytes and report 0xed/0x150[ c10a16e0 ] check object 0x150/0x210[ c10a1f22 ] free debug processing 0xd2/0x1b0[ c10a35ae ] kfree 0xfe/0x170[ c87f31c0 ] ? sectest exploit 0x1a0/0x1ec [sectest overwrite slub].[ c1002b97 ] sysenter do call 0x12/0x26FIX kmalloc-1024: Restoring 0xc7ac9018-0xc7ac9018P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: M EMORY P ROTECTIONIRight after boot the kernel write protects the pagesbelonging to:IIIthe kernel codethe read-only data (built-in firmware, kernel symboltable etc.)The non-executable bit is enabled for the pages ofread-only dataIand only on hardware that supports itP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: NULL PAGE M APPINGSILinux mmap(2) avoids NULL page mappings bymapping pages at addresses mmap min addrIImmap min addr defaults to 4096Two ways to configure mmap min addrIIvia a Linux Security Module (LSM)via Discretionary Access Control (DAC)IIIIsysctl vm.mmap min addr/proc/sys/vm/mmap min addrDEFAULT MMAP MIN ADDR kernel config optionmmap min addr max(LSM value, DAC value)P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: P OISON P OINTER VALUESIIIIPoison values: special values assigned to members offree’d (or uninitialized) kernel objectsThey help in identifying use-after-free bugsLIST POISON1 and LIST POISON2 are Poison values forpointers in linked lists (see include/linux/list.h)In x86 32 these pointer values default to:IIIILIST POISON1 0x00100100 (mappable address!)LIST POISON2 0x00200200 (ditto!)An attacker can exploit a use-after-free bug to force thekernel to dereference one of these and ultimatelyexecute his own code found in userspace [ATC2010]Mitigation: Provide a safe “base” for these pointers atcompile time (see ILLEGAL POINTER VALUE option)P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: K ERNEL M ODULESIIKernel code can be loaded at runtime from LinuxKernel Modules (LKM)LKM support is configurable at compile timeIIOnly root can load a module into the kernelIICONFIG MODULES optionCAP SYS MODULE capabilityModule code is placed in writable pages cat /proc/modulessectest 1162 0 [permanent], Live 0xc87f3000# grep 0xc87f3000 /debugfs/kernel page tables0xc87f3000-0xc87f40004KRWGLBxpteP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: K ERNEL M ODULESDemand Loading Trouble!I Kernel auto-loads a (possibly exploitable) module tofulfill a user’s requestIIExample #1: Unprivileged user creates socketIIrequest module("net-pf-%d", family);Kernel loads appropriate module for socket familyExample #2: Unauthenticated user connects USBstorage deviceIIKernel loads appropriate USB driverDesktop environment automatically mounts thedevice causing a filesystem module to be loadedP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

L INUX :: K ERNEL M ODULESDemand Loading Stock Kernels More Trouble!I Stock kernels contain modules for all kinds of h/w &s/w configurationsI .large attack surface that contains code that has notbeen rigorously testedI Remember the CAN bug ? (CVE-2010-2959)IIIIIDebian’s stock kernel comes with CAN modulesThe attacker creates a CAN socketThe kernel auto-loads the vulnerable module codeThe attacker exploits a bug in the CAN codeMitigationsIIInstall only the modules you needBlacklist unwanted modulesII/etc/modprobe.d/blacklistDisable module loading (at compile or run time)P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

G RSECURITY K ERNEL P ROTECTIONSPaXIIIIIIKERNEXEC – Non-Exec kernel pages (throughsegmentation)RANDKSTACK – Randomization of kernel stackMEMORY UDEREF – Protection against invalid userlandpointer dereferenceUSERCOPY – Bounds checking on heap objects whencopying to/from userlandMEMORY SANITIZE – Sanitization (zero-ing) of freedkernel pagesREFCOUNT – Kernel object reference counter overflowprotectionP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

G RSECURITY K ERNEL P ROTECTIONSOtherI KMEM – No kernel modification via /dev/mem,/dev/kmem, or /dev/portI IO – Privileged I/O can be disabled (ioperm, iopl)I VM86 – VM86 mode is restricted (CAP SYS RAWIO)I MODHARDEN – Module auto-loading only for rootI Poison pointer values with safe defaultsI HIDESYM, PROC, PROC USER, PROC ADD – Non-rootusers are denied access to kernel symbols and filesthat reveal kernel informationI GRKERNSEC DMESG – Access to dmesg(8) forbidden fornon-root usersP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWSIFocus on Windows 7 (NT 6.1)IIII/GS kernel stack cookieKernel pool safe unlinkingNULL page mappingsKernel ASLRP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: /GS KERNEL STACK COOKIEIIIIIThe /GS (buffer security check) Visual Studiocompiler option used when building core kernelcomponents and driversOn function start a value (cookie) is placed on thestack before the exception handler table and savedregistersOn function exit the value is checked to detect stackcorruptions32-bit cookie on 32-bit Windows64-bit (the top 16 bits of which are always clear) on64-bit WindowsP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: /GS BUFFERSIIProtects functions that have locally declared GSbuffersProtected:IIIIIchar buf[10];int buf[10]; // only in VS 2010struct { int i; char buf[10]; };struct { int a; int b; int c; int d; }; // only in VS 2010Not protected:IIIIchar buf[4];char *p[10];struct { int i; char *p; };struct { int a; int b; };P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: /GS COOKIE INITIALIZATIONkd u win32k!GsDriverEntrywin32k!GsDriverEntry:mov edi, edi8fc73d49 8bff8fc73d4b 55push ebpmov ebp, esp8fc73d4c 8bec8fc73d4e e8bdffffff call win32k! security init cookiekd uf win32k! security init cookie 0x12win32k! security init cookie 0x12:8fc73d22 a100f0c38f mov eax, dword ptr [win32k! imp KeTickCount]8fc73d27 8b00mov eax, dword ptr [eax]8fc73d29 356c63c58f xor eax, offset win32k! security cookiekd dd win32k! security cookie8fc5636c 8fc564ee 703a9b11 00000056 2b7731d58fc5637c 4e8bbd79 fcc6da94 180830a1 95baba28P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: /GS COOKIE USE AND CHECKkd uf win32k! SEH prolog4 GSwin32k! SEH prolog4 GS:.8fb1113d a16c63c58f mov eax, dword ptr [win32k! security cookie]xor dword ptr [ebp-4], eax8fb11142 3145fc8fb11145 33c5xor eax, ebp8fb11147 8945e4mov dword ptr [ebp-1Ch], eaxkd uf win32k! SEH epilog4 GSwin32k! SEH epilog4 GS:.8fb11168 8b4de4mov ecx, dword ptr [ebp-1Ch]8fb1116b 33cdxor ecx, ebp8fb1116d e846040100 call win32k! security check cookiekd uf win32k! security check cookiewin32k! security check cookie:8fb215b8 3b0d6c63c58f cmp ecx, dword ptr [win32k! security cookie]8fb215be 0f85da3f1100 jne win32k! report gsfailureP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: /GS KERNEL STACKPROTECTIONP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

I PV 6 P H ANDLE R OUTER A DVERTISEMENTIIIIIICMPv6 router advertisement vulnerabilityMS10-009 / CVE-2010-0239Remote code execution vulnerability due tounbounded memory copying when processingICMPv6 router advertisement packetsIPv6 enabled by defaultA success story for /GSP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

I PV 6 P H ANDLE R OUTER A DVERTISEMENTP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

I PV 6 P H ANDLE R OUTER A DVERTISEMENTP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: B YPASSING KERNEL /GSIIThere are two ways published in the literature tobypass the /GS kernel stack cookie [ATC2010]Both have requirements1. Overwrite the saved return address withoutcorrupting the cookieIControl the destination address of the memorycorruption2. Exception handler table’s functions don’t need to bein kernel memory and can be overwrittenIIException handler table exists, i.e. the target driverhas registered exceptionsTrigger an exception during or after the kernel stack’scorruptionP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: G UESSING THE KERNEL COOKIEIIWeak entropy sources are used for the /GS kernelcookie generation [JCH2011]The cookie is generated once per system sessionusing the following sources for entropy:IIIA successful prediction consists of calculatingIIIIIThe address of security cookieKeTickCount, i.e. the system tick count valuethe address of security cookie,the value of the EBP register,the system tick countAuthors calculated the prediction success rate ataround 46%Only applicable to drivers and modules not corekernel components (e.g. ntoskrnl.exe etc.)P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: K ERNEL POOL SAFEUNLINKINGIIIISafety checks for the kernel’s heap allocator to detectcorruptions of its metadataIntroduced to make harder the exploitation oftraditional generic unlinking attacksExploitation using fake allocator chunks to trigger anarbitrary write-4 primitiveMicrosoft’s implemented mitigation similar to safeunlinking present in other memory allocatorsP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: K ERNEL POOLkd dt nt! POOL DESCRIPTOR 0x000 PoolType : POOL TYPE 0x004 PagedLock : KGUARDED MUTEX 0x004 NonPagedLock : Uint4B 0x040 RunningAllocs : Int4B 0x044 RunningDeAllocs : Int4B 0x048 TotalBigPages : Int4B 0x04c ThreadsProcessingDeferrals : Int4B 0x050 TotalBytes : Uint4B 0x080 PoolIndex : Uint4B 0x0c0 TotalPages : Int4B 0x100 PendingFrees : Ptr32 Ptr32 Void 0x104 PendingFreeDepth : Int4B 0x140 ListHeads : [512] LIST ENTRY// 512 double linked lists that hold free pool chunksP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: L IST ENTRY AND POOL CHUNKHEADERkd dt nt! LIST ENTRY 0x000 Flink : Ptr32 LIST ENTRY 0x004 Blink : Ptr32 LIST ENTRYkd dt nt! POOL HEADER 0x000 PreviousSize : Pos 0, 9 Bits// BlockSize of previous chunk 0x000 PoolIndex : Pos 9, 7 Bits 0x002 BlockSize : Pos 0, 9 Bits 0x002 PoolType : Pos 9, 7 Bits 0x000 Ulong1 : Uint4B 0x004 PoolTag : Uint4B 0x004 AllocatorBackTraceIndex : Uint2B 0x006 PoolTagHash : Uint2BP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: U NLINKING OVERWRITEUnlink(Entry){.Flink Entry Flink; // whatBlink Entry Blink; // whereBlink Flink Flink; // (where) whatFlink Blink Blink; // (what 4) where.}P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: S AFE UNLINKINGExFreePoolWithTag(Entry, Tag){if(Entry BlockSize ! Flink ink Entry Flink; // whatBlink Entry Blink; // whereif(Flink Blink ! Entry) KeBugCheckEx();if(Blink Flink ! Entry) KeBugCheckEx();Blink Flink Flink; // (where) whatFlink Blink Blink; // (what 4) where.}P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: O THER POOL ALLOCATORATTACKSIFive attacks against the latest kernel pool allocator ofWindows 7 [KPL2011]1. Safe unlinking does not validate the LIST ENTRY ofthe pool chunk being unlinked, but of the ListHeadsthe chunk belongs to2. Lookaside (single linked) lists used for small poolchunks are not checked3. PendingFree (single linked) lists used for pool chunkswaiting to be freed are not checked4. The PoolIndex value of the POOL DESCRIPTORstructure is not checked and can be corrupted to pointto an attacker mapped NULL page5. Pool chunks (optionally) have a pointer to a processobject for reporting usage quotaP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: NULL PAGE MAPPINGSDWORD size 0x1000;unsigned char payload[] “\x41\x41\x41\x41 .”;LPVOID addr (LPVOID)0x00000004;// will be rounded to (), &addr, 0, &size,MEM RESERVE MEM COMMIT MEM TOP DOWN,PAGE EXECUTE READWRITE);memcpy((void *)addr, (void *)payload, sizeof(payload));kd u 000000000 4100000001 4100000002 4100000003 4100000004 4100000005 4100000006 41inc ecxinc ecxinc ecxinc ecxinc ecxinc ecxinc ecxP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

W INDOWS :: K ERNEL ASLRIIIINo full ASLR for important kernel structures (e.g.:page tables/directories), but poor man’s ASLR fordrivers and nt/hal6 bits on a 32-bit kernel, 8 bits on a 64-bit kernelThe Windows NT kernel (ntkrpamp.exe onSMP PAE, or generally nt) exports many functionsThe base address of nt needs to be foundkd !lmi ntModule: ntkrpampBase Address: 8280d000kd !lmi ntModule: ntkrpampBase Address: 8284e000I“Scandown” from a pointer within the nt mappinguntil the MZ checksum is found [WKP2005]P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

M AC OS XIIFocus on Snow Leopard 10.6.6By default 64-bit userland on 32-bit kernelIIIIIICan be forced to boot 64-bit kernelSecure virtual memory (i.e. encrypted swap)Separated kernel and process address spacesNo kernel stack smashing protectionsNo kernel memory allocator protectionsSome minor inconveniences for the attackerP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

M AC OS X :: S EPARATED ADDRESS SPACESIIIIOS X has separated kernel and process addressspacesContrary to systems that have the kernel mapped atthe virtual address space of every processUserland addresses cannot be dereferenced fromkernel memoryNULL page mappings allowed but irrelevantIIKernel NULL pointer dereferences becomeunexploitableCannot use userland addresses during exploitdevelopment to store fake structures/shellcode/etcP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

M AC OS X :: M INOR INCONVENIENCESIThe sysent (BSD system call table) symbol is notexported nm 140002a6242002a622eIkernel grep sysentThi64 sysenterThi sysenterTlo sysenterDnsysentSnsysent size checkDsystrace sysentTx86 sysenter arg store isvalidTx86 toggle sysenter arg storeThe mach trap table (Mach system calls) symbol isexported nm /mach kernel grep mach trap table00801520 Dmach trap tableP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

M AC OS X :: W RITABLE KERNEL PAGES(gdb) p sysent 6 {{sy narg 0, sy resv 0 ’\0’, sy flags 0 ’\0’,sy call 0x4954d9 nosys ,.sy call 0x483bc4 getrlimit , sy arg munge32 0x4f2d40 munge ww , sy arg munge64 0, sy return type 1,sy arg bytes 8}, {sy narg 2, sy resv 0 ’\0’,sy flags 0 ’\0’,.(gdb) p getrlimit 7 {int (struct proc *, struct getrlimit args *, int32 t *)}0x483bc4 getrlimit (gdb) x/x getrlimit0x483bc4 getrlimit :0x83e58955P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

M AC OS X :: W RITABLE KERNEL PAGES(gdb) display /i eip1: x/i eip 0x35b146 tcp connect 839 :(gdb) set edx 0x41414141(gdb) set edi getrlimit-0xcc(gdb) cContinuing.mov %edx, 0xcc(%edi)Program received signal SIGTRAP, Trace/breakpoint trap.0x0035b146 in tcp connect (tp 0x483af8, nam 0x21aa3ed8,p value temporarily unavailable, due to optimizations )at /SourceCache/xnu-1504.9.26/bsd/netinet/tcp usrreq.c:984984tp cc send CC INC(tcp ccgen);1: x/i eip 0x35b146 tcp connect 839 :mov %edx, 0xcc(%edi)P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

M AC OS X :: W RITABLE KERNEL PAGES(gdb) display /i eip1: x/i eip 0x35b146 tcp connect 839 :(gdb) set edx 0xcafebabe(gdb) set edi mk timer arm trap-0xcc(gdb) cContinuing.mov %edx, 0xcc(%edi)Program received signal SIGTRAP, Trace/breakpoint trap.0x0035b146 in tcp connect (tp 0x483af8, nam 0x21aa3ed8,p value temporarily unavailable, due to optimizations )at /SourceCache/xnu-1504.9.26/bsd/netinet/tcp usrreq.c:984984tp cc send CC INC(tcp ccgen);1: x/i eip 0x35b146 tcp connect 839 :mov %edx, 0xcc(%edi)P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

M AC OS X :: W RITABLE KERNEL PAGES(gdb) display /i eipmov %edx, 0xcc(%edi)1: x/i eip 0x35b146 tcp connect 839 :(gdb) set edx 0xcafebabe(gdb) x/x sysent0x82eee0 sysent :0x00000000(gdb) set edi 0x82eee0-0xcc(gdb) nikdp reply wait: error from kdp receive: receive timeout exceededkdp transaction (kdp fetch registers i386): transaction timed outP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

M AC OS X :: W RITABLE KERNEL PAGES(gdb) display /i eipmov %edx, 0xcc(%edi)1: x/i eip 0x35b146 tcp connect 839 :(gdb) set edx 0xcafebabe(gdb) x/x mach trap table0x801520 mach trap table :0x00000000(gdb) set edi 0x801520-0xcc(gdb) ni985if (taop tao ccsent ! 0 &&2: x/i eip 0x35b14c tcp connect 845 :mov 0x4(%eax), %ecx(gdb) x/x mach trap table0x801520 mach trap table :0xcafebabeP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSDIIIIIFocus on version 8.1 (latest stable)Kernel ProPolice/SSPRedZoneNULL page mappingsAll introduced in version 8.0P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSD :: P RO P OLICE /SSPIIsys/kern/stack protector.c implementsstack chk init() and stack chk fail()Event handler stack chk init() generates a randomcanary value on bootIIIICANARYGenerated with arc4rand()Placed between a protected function’s local variablesand saved frame pointerDuring the function’s epilogue the canary is checkedagainst its original valueIf it has been altered the kernel calls stack chk fail()which calls panic(9)P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSD :: C ANARY GENERATIONlong stack chk guard[8] {};.stack chk init(void *dummy unused){.long guard[ arraycount( stack chk guard)];arc4rand(guard, sizeof(guard), 0);for (i 0; i ¡ arraycount(guard); i )stack chk guard[i] guard[i];}P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSD ::IIIIRandom number generator based on the key streamgenerator of RC4Periodically reseeded with entropy from the Yarrowrandom number generator implemented in thekernel (256-bit variant)Yarrow collects entropy from hardware interruptsamong other sourcesFreeBSD’s /dev/random never blocks (like Linux’s/dev/urandom)IIARC 4 RAND ()May lead and has led to uniformity flaws [RND2004]Vulnerability in 2008: provided inadequate entropyto the kernel during boot time [FSA2008]P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSD :: C ANARY USE AND CHECKfunc:func 0x1:func 0x3:func 0x9:func 0xc:func 0x11:.func 0x33:func 0x36:func 0x3c:func 0x3e:func 0x3f:func 0x40:pushl %ebpmovl %esp, %ebpsubl 0x210, %espmovl 0xc(%ebp), %edxmovl stack chk guard, %eaxmovl %eax, 0xfffffffc(%ebp)movl 0xfffffffc(%ebp), %edxxorl stack chk guard, %edxjnz func 0x40leaveretcall stack chk failP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSD :: VARIABLE REORDERINGIIIILocal variables placed below local stack buffersFunction pointer arguments placed below localvariablesThat is local variables are placed at lower addressesfrom local stack buffersand function pointer arguments are placed at loweraddresses from local variablesP ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSD :: R ED Z ONEIIIOriented more towards debugging FreeBSD’s kernelmemory allocator (UMA - Universal MemoryAllocator) rather than exploitation mitigationDisabled by default: kernel needs to be recompiledwith DEBUG REDZONEPlaces guard buffers above and below each allocationdone via UMAmalloc(unsigned long size, struct malloc type *mtp, int flags){ .va uma zalloc(zone, flags);.va redzone setup(va, osize);free(void *addr, struct malloc type *mtp){ .redzone check(addr);P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSD :: R ED Z ONE SETUP AND CHECKredzone setup(caddr t raddr, u long nsize){ .haddr raddr redzone roundup(nsize) - REDZONE HSIZE;faddr haddr REDZONE HSIZE nsize;.memset(haddr, 0x42, REDZONE CHSIZE);memset(faddr, 0x42, REDZONE CFSIZE);redzone check(caddr t naddr){ ./* Look for buffer overflow. */ncorruptions 0;for (i 0; i REDZONE CFSIZE; i , faddr ) {if (*(u char *)faddr ! 0x42)ncorruptions ;P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSD :: NULL PAGE MAPPINGSIsysctl(8) variable security.bsd.map at zero enabledby default (i.e. the variable has the value 0)void *vptr;vptr mmap(0x0, PAGE SIZE, PROT READ PROT WRITE PROT EXEC, MAP ANON MAP FIXED, -1, 0);if(vptr MAP FAILED){perror(”mmap”);exit(EXIT FAILURE);} sysctl -a grep map at zerosecurity.bsd.map at zero: 0 ./mmapmmap: Invalid argument# sysctl -w security.bsd.map at zero 1 ./mmapmmap: 0x0P ROTECTING THE C ORE : K ERNEL E XPLOITATION M ITIGATIONS :: B LACK H AT EU 2011 :: C ENSUS , I NC .

F REE BSD ::IMAP AT ZEROFrom kern/kern exec.cstatic int map at zero 0;intexec new vmspace(image params *imgp, sysentvec *sv){.if (map at z

PROTECTING THE CORE: KERNEL EXPLOITATION MITIGATIONS:: BLACK HAT EU 2011 :: CENSUS, INC. USERLAND MEMORY CORRUPTION MITIGATIONS I Stack canaries I Protect metadata stored on the stack I Heap canaries I Guard value I Used to encode elements of important structures I Heap safe unlinking I Metadata sanitization I ASLR I Location of stack randomized I Random base address for dynamic libraries