csw2016 chen grassi-he-apple_graphics_is_compromised

62
Don't Trust Your Eye: Apple Graphics Is Compromised! Liang Chen (@chenliang0817) Marco Grassi (@marcograss) Qidan He (@flanker_hqd) CanSecWest Vancouver 2016

Upload: cansecwest

Post on 16-Apr-2017

1.761 views

Category:

Internet


0 download

TRANSCRIPT

Page 1: Csw2016 chen grassi-he-apple_graphics_is_compromised

Don'tTrustYourEye:AppleGraphicsIsCompromised!LiangChen (@chenliang0817)MarcoGrassi (@marcograss)Qidan He (@flanker_hqd)

CanSecWest Vancouver2016

Page 2: Csw2016 chen grassi-he-apple_graphics_is_compromised

AboutUs

• LiangChen• SeniorSecurityResearcher@Tencent KEENSecurityLab• Mainfocus:Browserexploitation,OSX/iOSsandboxescape

• MarcoGrassi• SeniorSecurityResearcher@Tencent KEENSecurityLab• Mainfocus:VulnerabilityResearch,OSX/iOS,Android,Sandboxes

• Qidan He• SeniorSecurityResearcher@Tencent KEENSecurityLab• Mainfocus:Vulnerabilityauditing/fuzzing,OS

Page 3: Csw2016 chen grassi-he-apple_graphics_is_compromised

Tencent KEENSecurityLab

• PreviouslyknownasKeenTeam

• AllresearchersmovedtoTencent becauseofbusinessrequirement

• Newname:TencentKEENSecurityLab

• YesterdayourunionteamwithTencentPCManager(Tencent SecurityTeamSniper)won“MasterofPwn”inPwn2Own2016

Page 4: Csw2016 chen grassi-he-apple_graphics_is_compromised

Agenda

• Applegraphicsoverview

• Fuzzingstrategy

• Casestudy

• Summary

Page 5: Csw2016 chen grassi-he-apple_graphics_is_compromised

Applegraphicsoverview

Page 6: Csw2016 chen grassi-he-apple_graphics_is_compromised

Whyattackthegraphicdrivers

• Thispartofthegraphicstacksisreachablefromthebrowsersandboxandresidesinthekernel.• Achievingkernelcodeexecutionwillgiveusprettymuchunrestrictedaccesstothetargetmachine.• EspeciallytruenowthatOSXintroduced“SystemIntegrityProtection”,oftengaininguserspace rootisnottheendoftheexploitationkillchain,youhavetocompromisethekerneltodisable“SIP”.• CompromisingthekernelbeforewasanecessityonlyoniOS,nowit’sstartingtobecomemorerelevantalsoonOSX.

Page 7: Csw2016 chen grassi-he-apple_graphics_is_compromised

SafariWebProcess sandboxattacksurface

• Youcanfindthe”com.apple.WebProcess.sb”sandboxprofileandseewhatisreachable(andtheimported“system.sb”).• (allowiokit-open• (iokit-connection"IOAccelerator")• (iokit-user-client-class"IOAccelerationUserClient")• (iokit-user-client-class"IOSurfaceRootUserClient")

• iokit-connectionallowsthesandboxedprocesstoopenalltheuserclient underthetargetIOService(muchlessrestrictivethaniokit-user-client-class)

Page 8: Csw2016 chen grassi-he-apple_graphics_is_compromised

UserClients underIntelAccelerator

UserClient Name Type

IGAccelSurface 0

IGAccelGLContext 1

IGAccel2DContext 2

IOAccelDisplayPipeUserClient2 4

IGAccelSharedUserClient 5

IGAccelDevice 6

IOAccelMemoryInfoUserClient 7IGAccelCLContext 8IGAccelCommandQueue 9IGAccelVideoContext 0x100

Page 9: Csw2016 chen grassi-he-apple_graphics_is_compromised

UserClients underIntelAccelerator

• Eachuserclient hasaIOService pointstoIntelAccelerator object

• IntelAccelerator objectisglobalunique• Createduponbooting

• MostoperationontheIntelAccelerator requiresLock(otherwisevulnerabletoraceconditionattack)• Exceptforsomereadoperations

Page 10: Csw2016 chen grassi-he-apple_graphics_is_compromised

UserClient Interface

• ImplementedbydifferentKexts

• Forexample:IGAccelGLContext• Method0x200– 0x206

• ClassIGAccelGLContext inAppleIntelBDWGraphics• Method0x100– 0x105

• ClassIOAccelGLContext inIOAcceleratorFamily2• Method0x0– 0x7

• ClassIOAccelContxt2inIOAcceleratorFamily2

• Evenwithinmethodcalls,itschildclass’smethodcanbecalledbecauseofpolymorphism

• Anyproblems?• Problem1:Doesthedeveloper fullyunderstandwhattheirparent’simplementationis?• Problem2:Doesthemethod implementerknowwhichfunctioncallhim,whatcheckisperformed?• Ifnot,vulnerabilitiesareintroduced

IGAccelGLContext IOAccelGLContext2 IOAccelContext2

AppleIntelHD5000Graphics IOAcceleratorFamily2 IOAcceleratorFamily2

Page 11: Csw2016 chen grassi-he-apple_graphics_is_compromised

Fuzzingstrategy

Page 12: Csw2016 chen grassi-he-apple_graphics_is_compromised

PassiveFuzzing

• Loadsome2Dor3Dgame/App• Writeadylib tohookIOKit APIs:• IOConnectMapMemory/IOConnectUnmapMemory• IOConnectCallMethod/IOConnectCallScalarMethod

• Randomlychangethecontentoftheparameters• IanBeerfromGoogleProjectZerodidit2yearsago.• FoundseveralbugsinprocessingsidebandbuffersinGLContext/CLContext::submit_data_buffers

Page 13: Csw2016 chen grassi-he-apple_graphics_is_compromised

PassiveFuzzing– ProsandCons

• Pros:• Easytoimplement• Evenforrandomfuzzing,itiseffective

• Cons:• Hardtoreproducetheissue• Cannotcoveralltheinterface

Page 14: Csw2016 chen grassi-he-apple_graphics_is_compromised

Activefuzzing

• Bysendingrandomdatatoeachinterface

• Needquitesomereverseengineeringworktoconstraintheuserinput• Otherwisenoteffective

• Howtomakeitmoreeffective?

Page 15: Csw2016 chen grassi-he-apple_graphics_is_compromised

Activefuzzing– HowtomakemoreeffectiveTIPS1

• Idealtargetforfuzzing:IGAccelSurface• Nottoomuchparametercheckbeforeperformcomplicatedoperation• IsmajorlycalledbyWindowServer process:

• NotsupposetobefrequentlyusedbySafari/UserApps• ManysituationsarenotwellconsideredwhenbeingcalledfromSafari/UserAppsdirectly.

• Severalcrashesbyfuzzingwiththissingleuserclient.

Page 16: Csw2016 chen grassi-he-apple_graphics_is_compromised

Activefuzzing– HowtomakemoreeffectiveTIPS2

• UsesimilarapproachforIGAccelGLContextwillnotgenerateanycrashes,why?• Theuserclient isbettertested.• GLcontextisnot initializedbyjustcalling

IOServiceOpen• Wemustmakeitsm_context tonon-NULL

• Twoapproaches:• InitializetheGLcontextbyrunningsomehelloworld

OpenGLapps,thenfindthemach_port oftheopenedGLContext userclient

• CallIOConnectAddClient toaddaIGAccelSharedUserClient tothenewlycreatedIGAccelGLContext• Willsetthem_context field

Page 17: Csw2016 chen grassi-he-apple_graphics_is_compromised

Activefuzzing– HowtomakemoreeffectiveTIPS3

• Userclientsareinter-connected

• Forexample• IfaIGAccelSurface userclientiscreated,itwillbeaddedtoIntelAccelerator::IOAccelSurfaceList• EachIGAccelSurface hasauniquesurfaceID,therearesystemcreatedIGAccelSurface (withSurfaceID1,2,0xffffffe0)• UsercreatedIGAccelSurface rangesitssurfaceIDfrom0x3– 0xffffffff• CanbeobtainedbycallingIOAccelDevice2::get_surface_info tobruteforceenumeratetheIDs• TheseIDscanbeusedtofuzz interfacesinotheruserclients (suchasIOAccel2DContext2::set_surface)

• Creatingalotofuserclientswithsuchrulesbuilt,willincreasetheeffectivenessalot.

Page 18: Csw2016 chen grassi-he-apple_graphics_is_compromised

Hybridfuzzing– combineactiveandpassivefuzzing

• Usedylid hooktorecordtheIOConnect call

• Foreachcall,dumpthemappedmemory(forexample,memorytype0,1,2forIGAccelGLContext)

• Duringactivefuzzing,givepossibilitytousetherecordedparameter

• Gotseveralcrashes

Page 19: Csw2016 chen grassi-he-apple_graphics_is_compromised

CaseStudy

Page 20: Csw2016 chen grassi-he-apple_graphics_is_compromised

IOKit vulnerability:CVE-????-????

• RaceconditioninanexternalMethod inAppleIntelBDWGraphics.• AffectseveryrecentMacwithIntelBroadwell CPU/Graphics.• DiscoveredbycodeauditingwhenlookingforsandboxescapesintoIOKit UserClients reachablefromtheSafariWebProcess sandbox.• Unfortunatelyitgotpartiallypatched1-2weeksbeforepwn2own!LLL .Areplacementwasneeded.L• UnpatchedinOSX10.11.3,onlypartialfixin10.11.4beta6.• Reliablyexploitable.• Wrong/partialfixmistakeresponsiblydisclosedtoApple.

Page 21: Csw2016 chen grassi-he-apple_graphics_is_compromised

IOKit vulnerability:CVE-????-????

• IGAccelCLContext andIGAccelGLContext are2UserClientsthatcanbereachedfromtheWebProcess Safarisandbox.• ThelockingmechanismsintheseUserClients isnottoogood,somemethodsexpectsonlyawellbehavedsinglethreadedaccess.• Firstwetargetedunmap_user_memory

Page 22: Csw2016 chen grassi-he-apple_graphics_is_compromised

IOKit vulnerability:someunsafecode

Page 23: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racecondition– Howtotriggerit?

1. OpenyourtargetUserClient (IGAccelCLContext)2. Callmap_user_memory toinsertoneelementintotheIGHashTable3. Callwith2racingthreadsunmap_user_memory.4. Repeat2and3untilyouareabletoexploittheracewindow.5. Doublefreeonfirsthand6. PROFIT!

Page 24: Csw2016 chen grassi-he-apple_graphics_is_compromised

Chanceofstableexploit?

• Theunmap raceisnotstable• Easytotriggernullpointerdereferenceifwe’reremoving*same*element• BoththreadspassesIGHashtable::contains• Onethreadremovesandwhenanotherdogets,NULLisreturned• Nocheckonreturnvalue

• Actuallyagoodnull-pointer-dereferencebug• ButcannotbypassSMAPandcannotusedasSandboxbypass

• Doublefreewindowissmall

Page 25: Csw2016 chen grassi-he-apple_graphics_is_compromised

Chanceofstableexploit?

• StructureofIGHashTable<unsignedlonglong,IGAccelMemoryMap>• Keyistheuserspace addressofpassedinmap_user_memory

• Whenmap_user_memory iscalled• ::containssearcheshashtable fordup

• Iteratethroughcorrespondingslot’shashlist anddomemcmp onkey• Ifnotfound,insertitandcreate/savereftoanIOAccelMemoryMap

• Whenunmap_user_memory iscalled• ::containssearchesagain• Iffound,call::removeandcallsavedIOAccelMemoryMap’s ptr’s releasevirtualfunction

Page 26: Csw2016 chen grassi-he-apple_graphics_is_compromised

IGHashTable structure

• struct IGVector• Int64currentSize• Int64capacity• Void*storage

• struct IGElement (orwhatevernameyourlike)• Vm_address_t address• IOAccelMemoryMap*memory• IGElement*next• IGElement*prevs

Page 27: Csw2016 chen grassi-he-apple_graphics_is_compromised

IGHashTable structure(cont.)

• struct IGHashTable::Slot• IGElement*elementHead• void*tail• Size_t linkedListSize

• Whenthehashtable isempty…init with16slots

Page 28: Csw2016 chen grassi-he-apple_graphics_is_compromised

IGHashTable insertion

• Whenmap_user_memory called• Retrieveshashindex usingpassedaddress• Ifslotalreadyoccupied

• AppendtotailoflinkedlistonSlot• When(totElemCnt – occupiedSlotCnt)/totElementCnt>0.51

• AndoccupiedSlotCnt/vecCapacity >26• Thehashtable slotswillbeexpanded*2

• Createnewslotvector, iteratealloldvaluesandaddintoit• Freeoldstorage(double freehere?)

Page 29: Csw2016 chen grassi-he-apple_graphics_is_compromised

IGHashTable examplefigure

• Whenelementisinserted• Slotislocatedusinghashfunction

Page 30: Csw2016 chen grassi-he-apple_graphics_is_compromised

IGHashTable examplefigure

• Whenelementisinsertedagain

Page 31: Csw2016 chen grassi-he-apple_graphics_is_compromised

IGHashTable examplefigure

• Whenelementisremoved• Locateslotusinghashindexfunction• Iterateallitemsonlist,compareforvalue(headQword)• Whenmatch,doremove

Page 32: Csw2016 chen grassi-he-apple_graphics_is_compromised

IGHashTable examplefigure

• Whenelementisremoved• Locateslotusinghashindexfunction• Iterateallitemsonlist,compareforvalue(headQword)• Whenmatch,doremove

Page 33: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racetounlink

• Calltwothreadstocontinuouslyremovetwo*adjacent**different*elements• Iftheremovefinishednormally• Justtryagain,nothingbadwillhappened

• Iftheremovefinished*abnormally*• We’llhaveafreedkalloc.32elementonlist!

• Next->prev =prev;• *prev =next;(prev->next=next)

Page 34: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racetounlink

Page 35: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racetounlink

Page 36: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racetounlink

Page 37: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racetounlink(ifracefailed)

Page 38: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racetounlink(ifracesuceed)

• Whenbeginslistis:• ele1->ele2->ele3->ele4

• ele2->prev =ele3• ele3->prev =ele4

• ele1->next=ele3• ele2->next=ele4

• Nowlistis(searchingusingnextptr):• ele1->ele3->ele4• Howeverele3isfreedactually!

Page 39: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racetounlink(ifracesucceed)

Page 40: Csw2016 chen grassi-he-apple_graphics_is_compromised

TurningintoUAF

• Fillingfreedholesusingio_service_open_extended• Callunmap_user_memory withtailaddressaftereachracetodetect• Ifracefailed,nothinghappensaslistisintact• Ifracesucceeded,containsandgetwilluseourcorruptedelement!

• Traversethelistandtriggervirtualcall• Unmap_user_memory

Page 41: Csw2016 chen grassi-he-apple_graphics_is_compromised

Craftfreeelementonlist

Page 42: Csw2016 chen grassi-he-apple_graphics_is_compromised

Crashwith0x4141414141414141

Page 43: Csw2016 chen grassi-he-apple_graphics_is_compromised

Next:controlRAXthenSuccessfullyRIPcontrolRAXisnowaspray-friendlyaddress

Page 44: Csw2016 chen grassi-he-apple_graphics_is_compromised

SuccessfullyRIPcontrolRAXisnowaspray-friendlyreachableheapaddress

RIPcontrolistrivial!

Page 45: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racecondition– thepartialfix

• ByreversingOSX10.11.4aroundbeta5wesadlynoticedthatAppleintroducedsomeadditionallocks.L

Page 46: Csw2016 chen grassi-he-apple_graphics_is_compromised

POC/EXPsoonavailableongithub

• https://github.com/flankerhqd/unmap_poc

Page 47: Csw2016 chen grassi-he-apple_graphics_is_compromised

Racecondition– thepartialfix

• UnfortunatelyforApple,thisfixisincompletein10.11.4betaX• Whosayswecanonlyraceunmap_user_memory?• This“add”operationinsidemap_user_memory isoutsideanylock!• Wecanracewith1thread unmap_user_memory andwithanothermap_user_memory forexample,tocorrupttheIGHashTable!

Page 48: Csw2016 chen grassi-he-apple_graphics_is_compromised

Turningitintoainfoleak

• Byracing::addand::remove,we’repossibletocraftadanglingelementconnectedby“prev”pointer.• AddOperation• cur->prev =*tail• Prev->next=cur• *tail=cur

• RemoveOperationontail• cur->prev->next=0• *tail=cur->prev

Page 49: Csw2016 chen grassi-he-apple_graphics_is_compromised

Turningitintoainfoleak

• Byracing::addand::remove,we’repossibletocraftadanglingelementconnectedby“prev”pointer.

Page 50: Csw2016 chen grassi-he-apple_graphics_is_compromised

Turningitintoainfoleak

• Byracing::addand::remove,we’repossibletocraftadanglingelementconnectedby“prev”pointer.

Page 51: Csw2016 chen grassi-he-apple_graphics_is_compromised

Turningitintoaninfoleak (CVE-2016-????)

• Thewindowissmallbutstillhassuccessrate• Roughlyafter10secswecangetapanic

• “Afreedzonehasbeenmodifiedatoffset0x10blabla….”(the“next”location)• POCwillbealsoavailableatflankerhqd/unmap_poc

• Wecangetaheapaddressifwecanfillinthefreedzonethenreadout• Usingopen_extendedpropertiesandreadoutproperties

• Ormore?Useimagination!

Page 52: Csw2016 chen grassi-he-apple_graphics_is_compromised

Turningitintoaninfoleak (CVE-2016-????)

• Thewindowissmallbutstillhassuccessrate• Roughlyafter10secswecangetapanic

• “Afreedzonehasbeenmodifiedatoffset0x10blabla….”(the“next”location)• POCwillbealsoavailableatflankerhqd/unmap_poc

• Wecangetaheapaddressifwecanfillinthefreedzone• Usingopen_extendedpropertiesandreadoutproperties

• Ormore?Useimagination!

Page 53: Csw2016 chen grassi-he-apple_graphics_is_compromised

kASLR infoleak:CVE-????-????

• OSXkernelimplementskernelAddressSpaceLayoutRandomization.• InordertodokernelROPforoursandboxescape,andbypassSMEP/SMAPmitigationswemustknowthekASLR slide.• Ainfoleak wasneeded!• FortunatelyIntelBDWgraphicdriverisverygenerous,andoffersalsoakASLR infoleak vulnerability!• Stillunpatchedin10.11.3and10.11.4betas,responsiblydisclosedtoApple.

Page 54: Csw2016 chen grassi-he-apple_graphics_is_compromised

kASLR infoleak:CVE-????-????

• ThistimewewilllookatanotherKEXTinBDWgraphicdriverstack:AppleIntelBDWGraphicsFramebuffer• ItaffectsthesameMacmodelsastheracediscussedbefore.• ThisparticularIOKit driverisleakinginformationinsidetheIOKitregistry,thatwillhelpustoguessthekASLR slide

Page 55: Csw2016 chen grassi-he-apple_graphics_is_compromised

• Thiscodesimplywillsetthe“fInterruptCallback”propertyinIOregistryasthePOINTERv3+3176.• ThisisnotaTEXTpointeraswewillsee,butthatallocationisdoneveryearlyinthebootprocess,thiswillallowustoguessthekASLR slideanywayevenwithoutanexactinformation.• ThisinformationcanbeleakedfromtheWebProcess Safarisandboxsoit’sperfecttohelpinakernelbasedsandboxescape.

Page 56: Csw2016 chen grassi-he-apple_graphics_is_compromised

kASLR infoleak:sometestsandexperiments

• Wewillretrievethe“fInterruptCallbacks”pointerseveraltimesafterreboot,inordertogetdifferentkernelrandomizationoffsets.• WewillretrievetherealkASLR slideeverytime,bydisablingSIPandrunningasrootaprogramthatleverages“kas_info”systemcall,thatallowsyoutogetthekASLR slideifyourunasrootandSIPisoff.

Testbed:

Page 57: Csw2016 chen grassi-he-apple_graphics_is_compromised

Focusontheredlinescolumns,thisisthe“band”ofinterestforkASLR slide,theotherpartsofthedifferenceIsirrelevanttoourpurposes.Asyoucanseewehaveonly3outcomesinthedifferencebetweentheleakandkASLR slide,0x9e7,0x9e8,0x9e9

Page 58: Csw2016 chen grassi-he-apple_graphics_is_compromised

kASLR infoleak:outcomes

• Withjustaquickanalysis,thankstothisinfoleak,wehaveimprovedourchancestopredictthekASLR slidefromaround1in256values(afullbyteofpossiblekASLR randomslides)tojust1in3.• Itcanbeprobablybeevenimprovedstatisticallysincethose3valuesseemstodon’thaveaequallydistributedprobability.

Page 59: Csw2016 chen grassi-he-apple_graphics_is_compromised

Summary

• Graphicdriversofferabigattacksurfacereachablefromthebrowsersandbox.• RaceconditionsinXNUareonlystartingtogetattentionbythesecuritycommunitynow.• OSXdeploysseveraleffectivemitigations (thinkaboutSMAP,notyetwidespreadonotherOses),butgoodexploitationtechniquesandgoodvulnerabilitiescanbypassthem.

Page 60: Csw2016 chen grassi-he-apple_graphics_is_compromised

Acknowledgments

• Qoobee• Wushi

Page 61: Csw2016 chen grassi-he-apple_graphics_is_compromised

Questions?

Twitter:@keen_lab

Page 62: Csw2016 chen grassi-he-apple_graphics_is_compromised