Copyright2016TrendMicroInc.1
$hellonEarth:FromBrowsertoSystemCompromiseMATTMOLINYAWE|ABDUL-AZIZHARIRI|JASIEL SPELMAN
Copyright2016TrendMicroInc.2
Introduction• SecurityResearchers
– MattMolinyawe- Twitter:@djmanilaice– Abdul-AzizHariri- Twitter: @abdhariri– Jasiel Spelman– Twitter:@WanderingGlitch
• TrendMicro– ZeroDayInitiative– World’sLargestVendorAgnosticBugBountyProgram– FocusedonVulnerabilityDiscoveryandRemediation– ResearchAdvancedExploitationTechniques– #1inVulnerabilities/CVEsforMicrosoftandAdobein2015
Copyright2016TrendMicroInc.4
ExploitMitigationsPriortoP2O2013• ASLR(AddressSpaceLayoutRandomization)• DEP(DataExecutionPrevention)• Sandboxingtechnology• Stackcookies• LowFragmentationHeap(Heaphardening)• JSJITmitigations• SEHOP
Copyright2016TrendMicroInc.5
ExploitMitigationsP2O2013- Present• 2013
– VTGuard – VirtualTable– ForceASLR– AppContainer– PoolIntegrityChecks– KernelASLR
• 2014– EMET– PartitionAlloc– Javaclicktoplay
• 2015– ControlFlowGuard– IsolatedHeap– MemoryProtection– win32kaccesspreventionin
Chrome
• 2016– AdobeFlashIsolatedHeap– AdobeFlashMemory
Protection
Copyright2016TrendMicroInc.6
HistoryofPwn2OwnRemoteBrowsertoKernelExploits• Pwn2Own2013- JonButlerandNils
– UsedatypeconfusionvulnerabilityinGoogleChromewithinSVGprocessing– Kernelvulnerability- NtUserMessageCall - exploitingapooloverflowinwin32k.sys
• Pwn2Own2014- SebastianApelt andAndreasSchmidt– TwoInternetExplorer11use-after-frees,whichevadedASLR/DEP– Kernelvulnerability- IOCTL0X1207FandIOCTL0X120C3AFD.sys danglingpointervulnerability
• Pwn2Own2015- PeterHlavaty,Jihui Lu,Zeguang Zhao(Team509),wushi (KeenTeam),WenXu,andJunMao(TencentPCMgr)– ExploitedheapbufferoverflowsinAdobeFlash– IntegeroverflowandachievedpoolcorruptionthroughTrueTypeFontvulnerabilities
• Pwn2Own2015– Mariusz Mlynski– Same-originpolicyviolationandresource://URLloadingprivilegedpages– UsedEMET’sWindowsInstallertouninstallEMET,whichledtoSYSTEMlevelprivileges
• Pwn2Own2015– JungHoon Lee(lokihardt)– BufferoverflowraceconditioninGoogleChromeandGoogleChromebeta– InfodisclosureandraceconditionwithintwoWindowskerneldrivers
Copyright2016TrendMicroInc.9
AppleSafariGraphicsContext UAF• Proofofconceptresultsinanaccessviolationinthedebugger
WebCore`WebCore::GraphicsContext::setPlatformTextDrawingMode:0x10dec437d <+13>: mov rdi, qword ptr [rax]
• Inpseudocode,thecrashishere:
result = **(WebCore::GraphicsContext ***)this;
Copyright2016TrendMicroInc.10
ExploitationSteps1. AttainedawriteprimitivefromtheUAFvulnerability
– InitialspraytoreclaimGraphicsContextobjectofsize0x100– PrimitivecomesfromWebCore::GraphicsContext::save()inSafari
qmemcpy((void *)(v3 + v4 + 16), (char *)this + 20, 0x4Du);
2. Secondspraywiththefollowingmemorylayout[String][Frame] [String][Frame] [String][Frame] [String][Frame]
3. BypassedASLRutilizingawriteprimitivetoenlargethestringobject’slengthandleakaFrameobject’svtable
4. AchievedexecutionwithROPandwritingavtable fortheframeobject– Calls.blur()whichcallsWebcore::jsElementPrototypeFunctionBlur
String Frame String Frame String Frame String Frame
Copyright2016TrendMicroInc.11
AppleOSXWindowServer MultiTouch UaF• _mthid_unserializeGestureConfiguration function
– CFData ischeckedandafreecanoccur– RaceconditioncanoccurwheretheCFData canbereclaimedbyanotherthread
if ( v2 ){
if ( !(unsigned __int8)_mthid_isGestureConfigurationValid(v2) )CFRelease(a1);
v1 = v2;}
Copyright2016TrendMicroInc.12
RaceConditionDetails• Invokedby_XSetGlobalForceConfig whichresidesin
CoreGraphics whichtheWindowServer utilizes• Shortlyafter_mthid_unserializeGestureConfiguration is
invoked,thereisanothercalltoaCFRelease
0x7fff88ec6ebd <+111>: call _mthid_unserializesGestureConfiguration;mov r15, raxtest r12, r12je 0x7fff88ec6ed2 ; <+132>mov rdi, r12call 0x7fff892c7c12 ; symbol stub for CFRelease
• Ifyouareabletoreclaimthedataintime,youcanfakeoutthemethodcallwithinobjc_msgSend whenCFRelease iscalledandgetdirectcodeexecution
Copyright2016TrendMicroInc.13
ExploitationSteps1. QuartzCore hasaserverthatisrunningwithinWindowServer2. TheserverportisacquiredthroughcallingCGSGetConnectionPortById3. SpraymemorywithCFDataCreateWithBytesNoCopy and
CGSPropertyListCreateSerializedData4. Inordertowinexploittheracecondition,call
CGSPropertyListCreateSerializedData whichsendsto_XRegisterClientOptions
5. Utilizeabufferofsize0x30andsendseveraltimes6. BuffercontainstheROPchainandshellcode7. Oncetheraceconditioniswon,codeisrunninginsideofWindowServer,and
rootexecutionisachievedsimplybycallingsetuid(0)
Copyright2016TrendMicroInc.18
AppleSafariTextTrack ObjectUaF• Ifm_cues isNULL andonlym_regions exists,setTrack(0) ontheitemsin
m_regions nevergetscalled.
TextTrack::~TextTrack(){if (m_cues) {
if (m_client)m_client->textTrackRemoveCues(this, m_cues.get());
for (size_t i = 0; i < m_cues->length(); ++i)m_cues->item(i)->setTrack(0);
if (m_regions) {for (size_t i = 0; i < m_regions->length(); ++i)
m_regions->item(i)->setTrack(0);}
}clearClient();}
Copyright2016TrendMicroInc.19
ExploitationSteps1. Leakaheapaddressoffofm_regions intheVTTRegionList object2. Aseriesofstringobjectsareallocatedaroundatrackelement3. Leakarbitraryaddresseswiththemodeattributefromthetrackelement4. SprayArrayBuffer objectsandcorrupttheaforementionedm_list attribute
– Achieveswriteprimitiveallowingforout-of-boundsreadandwriteaccess
5. ExecutionachievedthroughtheJavaScriptinterpreter– Assignsafunctiontooncuechange fromthecontrolledobject– Runtimeevaluatestheshellcode
var jit_func = new Function("return 0x1234;");jit_func();for (var i = 0, n = tracks.length; i < n; i++)
tracks[i].oncuechange = jit_func
Copyright2016TrendMicroInc.20
AppleOSXfontd Heap-basedBufferOverflow• fontd processprovidesthecom.apple.FontObjectsServer• Senda0x2emessagetoreachafunctionwhichallocatesmemoryofthe
sizeitreadsfromacontrolledpointer• DatapassedtoGetUncompressedBitmapRepresentation• GetUncompressedBitmapRepresentation functioncontainsno
boundschecking• Datacopiedintothebufferresultinginaheap-basedbufferoverflow
Copyright2016TrendMicroInc.21
ExploitationSteps1. Heapspraybysendingaseriesofmach_msg tothefontd process2. Triggertheheap-basedbufferoverflow3. UtilizingleaksofCoreFoundation andlibsystem_c withROPtechniquesto
callmprotect andgaincodeexecution
Copyright2016TrendMicroInc.22
AppleOSXfontd SandboxEscape• fontd processissandboxed• com.apple.fontd.internal.sb containsalistofnon-sandboxedapplications
– Locatedin/usr/share/sandbox
• FontValidator isnotsandboxed– UsesXT_FRAMEWORK_RESOURCES_PATH environmentvariableasapathtolookfor
libFontValidation.dylib
• Exploitstheenvironmentvariabletoescapethesandbox
Copyright2016TrendMicroInc.23
AppleOSXSubmitDiagInfo ArbitraryDirectoryCreation• /System/Library/CoreServices/SubmitDiagInfo runsasroot
– ProvidesandXPCservicecalled:com.apple.SubmitDiagInfo
• Method[Submitter sendToServerData:overrides:] readsvaluesfromthefollowingconfigurationfile:– /Library/Application
Support/CrashReporter/DiagnosticMessagesHistory.plist
• SubmitToLocalFolder keyallowsforanattackertowriteanarbitrarydirectory
Copyright2016TrendMicroInc.24
ExploitationSteps1. Createthefollowingdirectory
– /var/db/sudo/{USER_NAME}
2. Allowsthesudo commandtorunwithoutanypasswordauthentication
https://xkcd.com/149/
Copyright2016TrendMicroInc.27
GoogleChromeV8Out-Of-BoundsAccess• IterateElements
– Responsibleforvisitingelementswithanarray– Assumedelementaccesshadnosideeffects
• Customaccessor forarray– Modifyarraysizewhileitisbeingiterated
• Fixedinthesourcecoderepository– JustthreedaysbeforePwn2Own
Copyright2016TrendMicroInc.28
GoogleChromeV8Out-Of-BoundsAccessfunction evil_callback() {
delete Array.prototype[0];this.length=1; // Free the old storage
return 0.1;}
Array.prototype.__defineGetter__("0",evil_callback);
var arr=[];for(var i=1;i<3;i++)
arr[i] = 0.1;
arr = arr.concat();alert(arr);
Copyright2016TrendMicroInc.29
ExploitationSteps1. AllocateanArrayBuffer objectinthefreedstorage2. CraftacustomArrayBuffer object
– Arbitraryreadsandwrites
3. LeakaddresstoTextobject– Usedtofindbaseaddressofchrome_child.dll
4. Leakaddressofkernel32
Copyright2016TrendMicroInc.30
AdobeFlashAS2TransformUse-After-Free• flash.geom.Transform
– Containsamatrixproperty• Instanceofflash.geom.Matrix
• Customaccessor onflash.geom– ModifytheobjectbeforereturningtheoriginalMatrix
• Onlyusefulasaninformationleak
Copyright2016TrendMicroInc.31
AdobeFlashAS2TransformUse-After-Freevar mc:MovieClip = movies[movies.length - 0x100];var t = new Transform(mc);
var geom = _global["flash"]["geom"];var OriginalMatrix = flash.geom.Matrix;
geom.addProperty('Matrix',function() {for ( var i = movies.length - 0x200; i < movies.length; ++ i )
movies[i].removeMovieClip();return OriginalMatrix;
}, function() {} );
var m = t.matrix;
Copyright2016TrendMicroInc.32
ExploitationSteps1. Triggerthevulnerability2. Withinthecustomaccessor
1. FreetheMovieClip object2. Reclaimfreedmemorybyallocatingcustomobjects
3. Readvaluesfromthematrixproperty
Copyright2016TrendMicroInc.33
AdobeFlashAS2LoadVars Use-After-Free• LoadVars
– Containsadecodemethod• TakesURL-encodedstring• Setpropertiesonanobject
• Object.watch– Setacallbackonaproperty– Calledwhenthepropertyismodified
Copyright2016TrendMicroInc.34
AdobeFlashAS2LoadVars Use-After-Freevar mc:MovieClip = movies[movies.length - 0x200];var my_lv:LoadVars = new LoadVars();
mc.watch("aaa", function() {for ( var i = 200; i < movies.length; ++ i )
movies[i].removeMovieClip();});
try {my_lv.decode.call(mc, "aaa=1&bbb=2");} catch (e) { }
Copyright2016TrendMicroInc.35
ExploitationSteps1. Triggerthevulnerability2. Usethekernel32informationleaktobypassadynamiccall3. Decrementarbitraryaddress
1. Decrementreferencecountfromleakedcustomobject2. ReclaimfreedmemorybyallocatingByteArrays
4. ModifysizeofByteArray1. Arbitraryreadandwriteaccess
Copyright2016TrendMicroInc.36
MicrosoftWindowswin32kfull.sysSurfaceObjectUaF
• IssuearisesbecausethecodedoesnotproperlyhandlethereferencecountofaCompatibleDC object
• Windowobjectcreationhandledbywin32k• AssociatedSurfaceobjecthandledbyDesktopWindowManager• Cleanupmoreimportant
Copyright2016TrendMicroInc.37
ExploitationSteps1. Triggerthevulnerability2. Allocate AcceleratorTable objects3. Bitmapobjectusedformemoryaccess
– GetBitmapBits usedtoread– SetBitmapBits usedtowrite
Copyright2016TrendMicroInc.40
AdobeFlashAS2NetConnection TypeConfusion• AS2ScriptObjects contain:
– TypeID– Privatedataspecifictothetype
• Bothtypicallysetduringobjectconstruction– NotthecasewithNetConnection objects,whicharesetduring
connection
• Implicittypeconversionsduringfunctioncall– Allowforobjectmodification
Copyright2016TrendMicroInc.41
AdobeFlashAS2NetConnection TypeConfusion
var nc:NetConnection = new NetConnection()var o = this;o.toString = function() { super(); return "WIN 10,2,153,2"; }
var xml:XML = new XML("<mytag name='Val'> item </mytag>");xml.firstChild.attributes.aaa = o;
nc.connect.call(this, url, xml);
Copyright2016TrendMicroInc.42
ExploitationSteps1. ColorMatrixFilter objectsinterpretedasaNetConnection objects
– Containsanarrayof20floatsthatcanbemodified
2. Leakapointertoastring3. Triggeranarbitraryuse-after-free4. ModifyaByteArray object
– Read/writeaccesstomemory
Copyright2016TrendMicroInc.43
MicrosoftWindowsxxxEndDeferWindowPosEx WindowUaF
• Issuearisesbecausethecodedoesnotincrementareferencecountpriortocallinguserland code
• PostIAMShellHookMessageExmethodtakesaHWND– Doesnotverifythatitisstillvalid– TypicallydonebycallingValidateHwnd
void __stdcall PostIAMShellHookMessageEx(int a1, int a2, int a3) {if ( !a1 ) return;v3 = _gpsi;if ( !(*(_BYTE *)(*(_DWORD *)_gpsi + 1712) & 8) || !*(_DWORD *)(a1 + ?)? )return;
if ( a2 == 35 ) {v5 = *(_DWORD *)(*(_DWORD *)(a1 +4) +92);if ( v5 )_PostMessage(v5, *(_DWORD *)(*(_DWORD *)v3 + 520), a2, a3);
return;}v4 = *(_DWORD *)(*(_DWORD *)(_gSharedInfo + 8) * (unsigned __int16)a3);
Copyright2016TrendMicroInc.44
MicrosoftWindowsxxxEndDeferWindowPosEx WindowUaF
• xxxEndDeferWindowPosExmethod– CallsPostIAMShellHookMessageEx– DoesnotincrementtheWND referencecount
if ( v52 ) {v28 = *(_DWORD *)(v26 + v27 + 24);if ( v28 & 0xF0000000 ) {
if ( v28 & 0x10000000 ) {if ( *(_BYTE *)(v26 + v27 + 120) & 8 ) {
PostIAMShellHookMessageEx(*(_DWORD *)(*(_DWORD *)_gptiCurrent + 216), 21, v52);}//...if ( *(_DWORD *)(v45 + *((_DWORD *)v2 + 6) + 24) & 0x80000000 )
xxxSetTrayWindow(v3[54], 1);v26 = v45;
Copyright2016TrendMicroInc.45
ExploitationSteps1. WND replacedbyAcceleratorTable object2. Bitmapobjectsallocatedadjacent
– FirstBitmapusedtomodifypointerinsecondBitmap– GetBitmapBits usedtoread– SetBitmapBits usedtowrite
Copyright2016TrendMicroInc.48
AdobeFlashJPEG-XRParsingStack-basedBufferOverflow
• VariantofaGoogleProjectZerodiscovery– Nobodycheckedthe'else'branchofacondition
int k, i = 1;for (k = 0; k < num_nonzero; k+=1) {i += RLCoeffs[k*2];AdaptiveLPScan(image, LPInput[ndx], i, RLCoeffs[k*2+1]);i += 1;
}
Copyright2016TrendMicroInc.49
void __cdecl sub_108A208B(_DWORD *a1, int a2, signed int a3, int a4){unsigned int v4; // ecx@4unsigned int v5; // eax@5int v6; // eax@6int v7; // ecx@6
if ( !*a1 ) {if ( a3 > 0 ) {*(_DWORD *)(a2 + 4 * a1[a3 + 345]) = a4;v4 = ++a1[a3 + 360];if ( a3 > 1 ) {v5 = a1[a3 + 359];if ( v4 > v5 ) {a1[a3 + 360] = v5;v6 = a1[a3 + 344];a1[a3 + 359] = v4;v7 = a1[a3 + 345];a1[a3 + 345] = v6;a1[a3 + 344] = v7;
VulnerabilityinAdaptiveLPScan
Copyright2016TrendMicroInc.50
ExploitationSteps1. Triggervulnerabilityseveraltimes2. Leakstackaddress
– Usedtocraftafakeobjectpointer3. Modifytwoobjectsonthestack
– Onetoupdatepointersinthesecondobject– Theothertoperformarbitraryreadsandwrites
4. Return
Copyright2016TrendMicroInc.51
MicrosoftWindowsNtGdiGetEmbUFI InfoDisclosure• SimplycallingNtGdiGetEmbUFI issufficient• NtGdiGetEmbUFI returnsapointertoaPFFOBJ
– SupposedtoreturnanID– IssueisduetoGreGetUFI
if ( PFFOBJ::bInPrivatePFT((PFFOBJ *)&v23) ){*v8 |= 1u;if ( a7 )*(_DWORD *)a7 = *v16;
}
Copyright2016TrendMicroInc.52
MicrosoftWindowsPFFOBJ::bDeleteLoadRef FontUaF
• bDeleteLoadRef freesPFFOBJ resources• Returncodedependsonreferencecount• Callerwouldn’tknowifresourcesfreedornot
if ( v9 ){PFFOBJ::vKill(v5);v4 = 1;
}return *(_DWORD *)(*(_DWORD *)v5 + 44) == 0 ? v4 : 0;
Copyright2016TrendMicroInc.53
ExploitationSteps1. FreethePFFOBJ resources2. NtUserConvertMemHandle usedtoreclaimfreedmemory3. ResultsinaprimitivetoOR avaluewith2
– UsedtoincreaseaWND object’sextrabytesize
4. SetWindowLongPtr tosetpointerinotherWND– InternalGetWindowText toreadarbitrarymemory– NtUserDefSetText towritearbitrarymemory
Copyright2016TrendMicroInc.56
MicrosoftEdgeJavaScriptConcat MethodUninitializedVariable
• FromJavascriptArray::ConcatArgs
Var subItem;uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem){
if (JavascriptOperators::HasItem(itemObject, idxSubItem)){
JavascriptOperators::GetItem(itemObject, idxSubItem, &subItem, scriptContext);if (pDestArray){
pDestArray->DirectSetItemAt(idxDest, subItem);
Copyright2016TrendMicroInc.57
ExploitationSteps• SimpleTrigger
var bug = new Proxy(new Array(1),{has: ()=> true});alert(bug.concat());
1. SprayJavascriptDate objectsofsize0x902. PushoneoftheJavascriptDate objects,whichresidedinthemiddleofthe
spraydeepinthestackusingArray.slice3. Freememory4. SprayDataView objectatthefreedspace5. Triggerthevulnerabilitytogetthereferencetothepointerthatwepushedin
step2
Copyright2016TrendMicroInc.58
ExploitationSteps• Objectthatwillbereferencedusingthevulnerabilityisthelast
JavascriptDate objectwhichpointstoDataView+0x30
• ThefollowingisarepresentationoftheDataView objectstructure:+0x00 +0x08
0x00 *vtable *type
0x10 N/A N/A
0x20 length *arrayBuffer
0x30 byteOffset *data
Copyright2016TrendMicroInc.59
ExploitationSteps• Readandwriteprimitives
– DataView objectsmemoryisfreedandfilledwithNativeFloatArrayobjects
– AslongasthesizeofNativeFloatArray issmall,elementsforthearrayarecreatednexttoeachother
– FakeDataView objectsarecreatedtoperformread/writefromprocessmemory
• ControlFlowGuardbypass– Useasetjmp calltoobtainthestackaddressandoverwritethereturn
address
Copyright2016TrendMicroInc.60
MicrosoftWindowsDiagnosticsHubStandardCollectorDirectoryTraversal
• StandardCollectorisSYSTEM-levelCOMservice– CommunicationispossiblefromwithintheMicrosoftEdge'ssandbox
• COMinterfaceexposestheAddAgent functionthattakestwoarguments– DLLpath– GUID
Copyright2016TrendMicroInc.64
MicrosoftEdgeJavaScriptfill Out-of-BoundsAccess• Lengthisfetchedfromthelengthproperty• Lengthpropertycanbeoverwrittenincertaincases
Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...){
//....
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
Copyright2016TrendMicroInc.65
ExecutionFlowVar JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
{//...int64 end = mxin<int64>(finalVal, MaxArrayLength);uint32 u32k = static_cast<uint32>(k);
while (u32k < end){
if (typedArrayBase) {typedArrayBaseypedArrayBase->DirectSetItem(u32k, fillValue, false);
} else if (pArr){
pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);}
Copyright2016TrendMicroInc.66
ExecutionFlow__inline BOOL BaseTypedDirectSetItem(__in uint32 index, __in Js::Var value, __in bool skipSetElement, TypeName(*convFunc)(Var value, ScriptContext* scriptContext)){// This call can potentially invoke user code, and may end up detaching the underlying array (this).// Therefore it was brought out and above the IsDetached checkTypeName typedValue = convFunc(value, GetScriptContext());
if (this->IsDetachedBuffer()) // 9.4.5.9 IntegerIndexedElementSet {JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_DetachedTypedArray);}
if (skipSetElement) { return FALSE; }
AssertMsg(index < GetLength(), "Trying to set out of bound index for typed array.");Assert((index + 1)* sizeof(TypeName) + GetByteOffset() <= GetArrayBuffer()->GetByteLength());TypeName* typedBuffer = (TypeName*)buffer;typedBuffer[index] = typedValue;
Copyright2016TrendMicroInc.67
ExploitationSteps• Simpletrigger
var ua = new Uint32Array(0x10);ua.__proto__= new Array(0xffffffff); ua.fill(0x41, 0x41414141, 0x41414141 + 1);
• CorruptthelengthofaJavascriptNativeIntArray– Achievesarbitraryreadandwrite
• Twoheapsprayswereusedduringtheexploitationprocess– Firstonetostabilizetheheap– Secondonetofetchtheindex
Copyright2016TrendMicroInc.68
ExploitationSteps• Readandwriteprimitive
– Oncetheindexofthetargetobjectwasfound,thebugwastriggeredagainsttheobjecttooverwritethelengthwith0x7FFFFFFC
– Usingthiscorruptedobject,arbitraryread/writeispossibleagainstalargechunkoftheChakraheap
• ControlFlowGuardbypass– Useasetjmp calltoobtainthestackaddressandoverwritethereturn
address
Copyright2016TrendMicroInc.69
MicrosoftWindowsDxgkrnl DriverBufferOverflow• dxgkrnl.sys kerneldriverhasastructurecalled_D3DKMT_PRESENTHISTORYTOKEN
– Token andTokenSizemembersvaryaccordingtotheModelmember– ThereisamodelcalledFlip model– Flipmodel'scorrespondingtokenstructureisD3DKMT_FLIPMODEL_PRESENTHISTORYTOKEN
• _D3DKMT_PRESENTHISTORYTOKEN structurecontainsastructurecalledD3DKMT_DIRTYREGIONS
• D3DKMT_DIRTYREGIONS containsanarrayofRECTS
typedef struct _D3DKMT_DIRTYREGIONS{UINT NumRects;RECT Rects[D3DKMT_MAX_PRESENT_HISTORY_RECTS];} D3DKMT_DIRTYREGIONS;
Copyright2016TrendMicroInc.70
MicrosoftWindowsDxgkrnl DriverBufferOverflow• DrivercheckswhetherNumRects isgreaterthan
D3DKMT_MAX_PRESENT_HISTORY_RECTS:
cmp dword ptr [r15+334h], 10h ; jumptable 00000001C0098BBB case 1jbe short loc_1C0098C0Bcall cs:__imp_WdLogNewEntry5_WdAssertionmov rcx, raxmov qword ptr [rax+18h], 38hcall cs:__imp_WdLogEvent5_WdAssertion
loc_1C0098C0B:mov eax, [r15+334h]shl eax, 4add eax, 338hjmp short loc_1C0098C7D
Copyright2016TrendMicroInc.71
MicrosoftWindowsDxgkrnl DriverBufferOverflow
• Executioncontinuesafterloggingtheviolation• Codereachesloc_1C0098C7D regardlessofthevaluespecifiedfor
NumRects:
loc_1C0098C7D:lea r8d, [rax+7]mov rdx, r15 ; Srcmov eax, 0FFFFFF8hmov rcx, rsi ; Dstand r8, rax ; Sizecall memmove
Copyright2016TrendMicroInc.72
ExploitationSteps1. Triggeroverflowvulnerabilitytooverwriteasubsequenthistorytokenrecord2. Whentherecordisread,theaddressthatwasspecified(duringtheoverwrite)willactuallybe
read3. BITMAP objectsaresprayedintothekernelmemorypool
– AddressoftheseBITMAP objectscanbeguessedusingtheGDIhandletable,whichcanbeaccessedwithuser32!gSharedInfo
4. Usingthataddress,arbitrarydatacanbewritten5. ThespecificBITMAP objectthatwaswrittento,canbefoundbytraversingthesprayed
BITMAP objects6. Kernel-modereadandwritecanbeachievedusingSetBitmapBits andGetBitmapBits
APIsonthiscorruptedBITMAP object7. IDTtablecanbedumped andthentoskrnl baseaddresscanbefetched8. Systemprocessandthecurrentprocess' EPROCESS structurescanbefetchedbytraversing
thePspCidTable
Copyright2016TrendMicroInc.74
Conclusion• Applicationsandboxingisastepintherightdirection• Kernelattacksurfaceremainsexpansiveandexposed• Exploitationisgettingharder…butstillverypossible
– Writeexploitprimitivesareamainstayinexploits– Logicbugscanbehighimpact
• Vulnerability/Exploitresearchisbecomingincreasinglypopular;-)– Newresearcherssettinganewstandard– Becomingateamsport