82

drill the apple core 11 20 - Black Hat Briefings · 2018-11-30 · 530 BSD API Patterns VM Fusion Support macOS Executor XNU ... operation leaves the rest of this page filled with

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Juwei Lin

- @panicaII- Joined TrendMicro Since 2013- Windows Kernel/Rootkit/Bootkit- Ransomware Decryption- iOS/Android/Mac Vulnerability Hunting

LilangWu

- @Lilang_Wu- Joined Trend Micro Since 2016- Mac/iOS Vulnerability/Malware- iOS/Android Exploit Detection

MoonyLi

- @Flyic- 8 years security- Sandcastle - Deep Discovery- Exploit Detection- Mac/Windows Kernel - iOS/Android Vulnerability

Agenda

• Smart Fuzz XPC• XPCInternals• FuzzStrategy• ReproduceStrategy• Output

Agenda

• Smart Fuzz XNU• Introduction• ArchitectureandSanitizerSupport• SyntaxEngineandCorpus• Sanitizers• RootCaseStudy

Agenda

Smart Fuzzing XPC

•WhatisXPC?• low-level(libSystem)interprocess communicationmechanism• simplemessagesandcomplexmessages

msgh_bits

msgh_size

msgh_remote_port

msgh_local_port

msgh_voucher_port

msgh_id

msgh_descriptor_count

descriptor#1

descriptor#2

...

Trailer

mach_msg_type_descriptor_t

24bytes

c

descriptorcount

msgh_bits

msgh_size

msgh_remote_port

msgh_local_port

msgh_voucher_port

msgh_id

msgh_descriptor_count

ooldescriptor#1

ooldescriptor#2

...

Trailer

mach_msg_ool_descriptor_t

24bytes

c

descriptorcount

• MessageBinaryFormat

• XPCServices• `launchctl dumpstate`

• AttackSurface• serialize/deserialize• libxpc• servicescode

Kernel

Services

processA

MachMessages

XPCmechanism

CoreMedia/Audio/...

xpc_datadeserialize

libxpcxpc_*

servicescode

CraftedMachMessage

• Howtotriggerthesebugs?

• Proactivefuzz

•FuzzStrategy• Easytocontrol

• Easytomutate

• Easytomonitor

• Easytoreproduce

XPC Libxpc.dylib / xpc_*

ServicesAudio CoreMedia

Windowserver iohideventsystem

Foundation.framework / NSXPC*

MachMessageExecutor CrashMonitor

Reproduce

Seedserver

RandomizerwithSeed

FuzzeragentMutationEngine

Seedreproducer

【2】fuzztargetwithseed

【3】Monitorprocessstatus

【1】mutationwithseed

【4】reporducebyseed

• FuzzControllerüWrapthexpc interfacesbypython

üPythonfuzzEngine

•Mutation• Pseudo-RandomNumberGeneratorwithMersenne TwisterAlgorithm

• CrashMonitor• MonitortheprocessesIDsclusterstatus• Monitorexitssignalvalue

TypicalExample

Storage Cost Speed Cost SupportComplexScenario

ReproduceRate

DevEffort

Log Trinity High(Execution Log)

High Low Low Low

Case(File) AFL Middle(Files Causing Crash)

Low Middle Middle High

Crash Dump - High(Every Crash Context)

High - Very Low No

Seed JS Fun Fuzz Low(Integer)

Low High High Low

• ComparisonbetweendifferentReproduceMethods

Target0:(fontd)stopped.(lldb)bt*thread#1,queue='com.apple.main-thread',stopreason=EXC_BAD_ACCESS(code=1,address=0x7ffee1934000)*frame#0:0x00007fff55a06f49libsystem_platform.dylib`_platform_memmove$VARIANT$Haswell +41frame#1:0x00007fff2b8b597alibATSServer.dylib`FODBWriteToAnnex +246frame#2:0x00007fff2b8d0157libATSServer.dylib`HandleFontManagementMessage +5403frame#3:0x00007fff2b8cd2d1libATSServer.dylib`serverMainHandler(__CFMachPort*,FontMgrMessage*,long,void*)+263frame#4:0x00007fff2d3e4596CoreFoundation`__CFMachPortPerform +310frame#5:0x00007fff2d3e4449CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__+41frame#6:0x00007fff2d3e4395CoreFoundation`__CFRunLoopDoSource1+533frame#7:0x00007fff2d3dbf50CoreFoundation`__CFRunLoopRun +2848frame#8:0x00007fff2d3db1a3CoreFoundation`CFRunLoopRunSpecific +483frame#9:0x00007fff2d419c33CoreFoundation`CFRunLoopRun +99frame#10:0x00007fff2b8cc91clibATSServer.dylib`main_handler +4510frame#11:0x00007fff556f5015libdyld.dylib`start +1frame#12:0x00007fff556f5015libdyld.dylib`start +1

• CaseStudy- CVE-2018-4411

SmartFuzzingXNU

Smart Fuzzing XNU

• IntroductionofSmartFuzzingXNU• ArchitectureandSanitizerSupport• SyntaxEngineandCorpus• Sanitizers• RootCaseStudy

WhatIwillintroducetoday

1.PortSyzkaller toSupportmacOS XNUFuzzing.

2.ModifyXNUtoaddsupportsomefeatures.

Fuzzer

530 BSD API Patterns

VM Fusion Support

macOS Executor

XNU

Add Code Coverage

Add Kernel Memory Sanitizer

Enable Kernel Address Sanitizer

1. Key modules are in GREEN

2. Also add some other modules,e.g. vmfusion

Architecture

APIPattern CodeCoverage

• Syntax Engine is directly from Syzkaller; But I developed the XNU BSD APIpatterns.• Kasan is from XNU, but it does not work wellaftercompilation.• I developed coverage sanitizer.• I developed kmsan.

MyEfforts

Syntax Engine & Corpus

syz-extract &syz-sysgen

• descriptionin txt writtenby human

generationengine

• descriptionin go madeby previous 2tools

executor

• programmade bypreviousgenerationengine

Quick glance at syzkaller’s syntax engine

Corpus

• Morethan500syscalls inXNUkernel

• Refertosyzkaller’s syscall descriptionssyntax:https://github.com/google/syzkaller/blob/master/docs/syscall_descriptions_syntax.md

• Refertosampletxtfilesinsyzkaller project

Sanitizers

Name Features Comments

AddressSanitizer2 • Out-of-boundsaccessestoheap,stackandglobals• Use-after-free• Use-after-return• Use-after-scope• Double-free,invalidfree

• compilerinstrumentationmodule• run-timelibrary

MemorySanitizer3 • uninitializedreads

SanitizerCoverage4 • get function/block/edge coverage • Instrumentations• Default callbacks provided

... • ThreadSanitizer5• UndefinedBehaviorSanitizer6• DataflowSanitizer7• LeakSanitizer8

Basic Concepts 1: User Mode Sanitizers1

Basic Concepts 2: Kernel Mode SanitizersName Features Comments

Kernel Sanitizer Coverage • get function/block/edge coverage • Has instrumentations support• NO existing callbacks implementation

KASAN(kernel address sanitizer)

• Out-of-boundsaccessesUse-after-free• Use-after-return• Use-after-scope• Double-free,invalidfree

• Has instrumentations support• Has callbacks/module support

KMSAN(kernel memory sanitizer)

• uninitializedreads • Not implemented

• We need to develop a new module in XNU to:

• Support sanitizer callback function

• Read the coverage data back to user fuzzing program

Sanitizer Coverage

1. callback name:__sanitizer_cov_trace_pc

2. just support single-thread mode

3. store coverage structure into task_t

Callback Implementation

After Compilation

• latest XNU has KASAN support• KDKnowprovideskernel.kasan whichworkswell.• It does not work ifyoucompileit,VMcannotboot.

• It consists of guard pages, shadow memory and operations.

• ItcanprotectGlobals,StackandHeapmemory.

KASAN

1) memoryoperationsarecalled,e.g.__asan_strlcpy

2) __asan_strlcpy checksshadowmemory

3) KASANpanicsthekernelifshadowmemoryisillegal(shadowvalue<0)

HowKASANprotectsmemory

Guard Pages & Shadow Memory

HeapMemoryOperations StackMemoryOperations OtherMemoryOperations

__asan_bcopy __asan_stack_malloc_0 __asan_load1

__asan_memmove __asan_stack_malloc_1 __asan_load2

__asan_memcpy __asan_stack_malloc_2 __asan_load4

__asan_memset __asan_stack_malloc_3 __asan_load8

__asan_bzero __asan_stack_malloc_4 __asan_load16

__asan_bcmp __asan_stack_malloc_5 __asan_loadN

__asan_memcmp __asan_stack_malloc_6

__asan_strlcpy __asan_stack_malloc_7

__asan_strlcat __asan_stack_malloc_8

__asan_strncpy __asan_stack_malloc_9

__asan_strncat __asan_stack_malloc_10

__asan_strnlen

__asan_strlen

#definestrlcpy __asan_strlcpy -fsanitizer=address buildin callsinxnu sourcecode

Operations

• When new memory is allocated and aligned with 8

Example: Detect UAF

• When the memory is freed

Example cont. 1

• When the memory is used after free, any related operation will check itsshadow memory and then panic the system.• 0xffisillegal

Example cont. 2

• Kernel memory sanitizer is used to detect uninitialized memory.

• We worked on how to initialize all uninitialized memory allocated in kernel,e.g. kalloc_canblock

KMSAN

kalloc_canblock

Check in fuzzer1. check continuous `0xDE`

2. add a syscall ‘panicall_report’

SyntaxEngine Sanitizers

SmartXNUFuzzer

• About 530API patterns

• Corpus

• CoverageSanitizer

• KASAN• KMSAN

Conclusion

macOS RootCaseStudy

CVE-2018-4413• Uninitializedheapmemoryleak• FixedinmacOS 10.14.1andiOS12.1• Canbeusedtoleakipc_port objectaddress

CVE-2018-4425• NECPtypeconfusion• FixedinmacOS 10.14• Canbeusedtowritearbitrarykerneladdress• Canbeusedtofreearbitrarykerneladdress

CVE-2018-4413sysctl_procargsx isusedtoretrieveprocessargsinformationbycallingsysctl.

atlocation(a):• p->p_argslen isusuallyaround0x300;• Isetmyarg_size to0x200 sothatarg_size willnot

beround_paged

CVE-2018-4413

Atlocation(b):• Stackinformationiscopiedtonewallocated

pageatoffset0witharg_size (0x200).• Thenewallocatedpageisnotzeroed.Sothis

operationleavestherestofthispagefilledwithuninitializedheapdata.

Atlocation(c):• copy_end isround_paged,

parameter data pointstothelast0x200bytesofthepage.

Atlocation(d):• copyout the0x200bytesleakedheap

informationtouserbuffer

uninitializedheapdata1Args Information(arg_size,0x200)

uninitializedheapdata2(arg_size,0x200)

copy_enddatapagestart

leaked!!!

Exploit CVE-2018-4413toleakipc_port objectaddress:

MACH_MSG_OOL_PORTS_DESCRIPTOR Triggerthevulnerabilitytoleaktheportsmemory:

Destroytheportsmemory:

Applefixeditbycallingbzero.

CVE-2018-4413

CVE-2018-4425NECPAttackSurface1

necp_open necp_client_action

necp_client_addnecp_client_removenecp_client_copynecp_client_list

necp_client_agent_actionnecp_client_copy_agentnecp_client_agent_use

necp_client_copy_interfacenecp_client_copy_route_statisticsnecp_client_update_cachenecp_client_copy_client_update

necp_fd_data

CVE-2018-4425NECPAttackSurface1

necp_open assignsnecp_fd_data tofg_data:• user-modesyscall getsreturnedfd handle• fd isanindextokernelfp object• fp objectcontainsnecp_fd_data objectasfg_data

necp_client_action operatesonfg_data:• at(a),callnecp_find_fd_data tofind

necp_fd_data withgivenhandle• dispatchmethodsoperateson

necp_fd_data

CVE-2018-4425NECPAttackSurface1

necp_find_fd_data findsfd_data:• callfp_lookup togetfp ofgivenfd• at(b),verifyifthefp isoftype

necp_fd_data bycheckingfo_type

CVE-2018-4425NECPAttackSurface1

CVE-2018-4425NECPAttackSurface1

NormalProcess:

• necp_open createsnecp_fd_data objectinkernelandreturnshandletousermode

• necp_client_action findsthenecp_fd_data bygivenhandle,itinternallychecksifcorrespondingfo_typeequalsDTYPE_NETPOLICY

• dispatchmethodsofnecp_client_action operatesonfoundnecp_fd_data

CVE-2018-4425NECPAttackSurface2

necp_session_open necp_session_action

necp_session_add_policynecp_session_get_policynecp_session_delete_policynecp_session_apply_all

necp_session_list_allnecp_session_delete_allnecp_session_set_session_priority

necp_session_lock_to_processnecp_session_register_servicenecp_session_unregister_servicenecp_session_dump_all

necp_session

CVE-2018-4425NECPAttackSurface2

necp_session openassignsnecp_session tofg_data:• user-modesyscall getsreturnedfd handle• fd isanindextokernelfp object• fp objectcontainsnecp_session objectasfg_data

CVE-2018-4425NECPAttackSurface2

necp_session_action operatesonfg_data:• at(aa),callnecp_session_find_from_fd to

findnecp_session withgivenhandle• dispatchmethodsoperateson

necp_session object

CVE-2018-4425NECPAttackSurface2

necp_session_find_from_fd findsfd_data:• callfp_lookup togetfp ofgivenfd• at(bb),verifyifthefp isoftypenecp_session by

checkingfo_type

CVE-2018-4425NECPAttackSurface2

NormalProcess:

• necp_session_open createsnecp_session objectinkernelandreturnshandletousermode

• necp_session_action findsthenecp_session bygivenhandle,itinternallychecksifcorrespondingfo_type equalsDTYPE_NETPOLICY

• dispatchmethodsofnecp_session_action operatesonfoundnecp_session

CVE-2018-4425TypeConfusion

Attacksurface1:iffp->...->fo_type ==DTYPE_NETPOLICY,fp isoftypenecp_fd_data

Attacksurface2:iffp->...->fo_type ==DTYPE_NETPOLICY,fp isoftypenecp_session

necp_fd_data is totallydifferentfromnecp_session!!!

Whatwelearnsofar:

CVE-2018-4425Exploit:arbitraryaddressfree

Method:1. createnecp_fd_data objectandcallnecp_session_action tooperateonit

2. createnecp_session objectandcallnecp_client_action tooperateonit

CVE-2018-4425Exploit:arbitraryaddressfree

Step1 callnecp_open tocreatenecp_fd_data object:• fd_data->update_list isinitializedbyTAILQ_INIT

+20:0+28:update_list address

CVE-2018-4425Exploit:arbitraryaddressfree

necp_open +0x20:0+0x28:update_list address

CVE-2018-4425Exploit:arbitraryaddressfree

Step2callnecp_session_action ontheobject

atlocation(b),ifsession->proc_locked isfalse(0),session->proc_uuid andsession->proc_pid willbeupdated.

CVE-2018-4425Exploit:arbitraryaddressfree

• session->proc_locked atoffset0x20overlapsupdate_list whichis0 innecp_fd_data.

• session->proc_uuid atoffset0x21isupdatedwithmachoUUID

• session->proc_pid isupdatedwithcurrentpid

CVE-2018-4425Exploit:arbitraryaddressfree

+0x20:0+0x28:update_list address

+0x20:0+0x21:UUID,low7Bytes+0x28:UUID,high9Bytes+0x34:pid

necp_session_action

CVE-2018-4425Exploit:arbitraryaddressfree

Step3callnecp_client_action ontheobject• weuseaction15(necp_client_copy_client_update)• atlocation(f),client_update isfreed• client_update isthefirstelementofupdate_list

whichisUUIDnow

CVE-2018-4425Exploit:arbitraryaddressfree

+0x20:0+0x28:update_list address

+0x20:0+0x21:UUID,low7Bytes+0x28:UUID,high9Bytes+0x34:pid

necp_session_action necp_client_actionFREEAddress(0x20– 0x28)

ForExample,wesetMachO UUID(16bytes)as41414141414141414141414141414141,hereweget0x4141414141414100freed.Wecancontrolhigh7bytesoftheaddresstobefreed.

CVE-2018-4425AppleFix

Addsubtypecheck:necp_session hassubtype1necp_fd_data hassubtype2

• Support kernel extension• Support IOKit(+codecoverage)• Support Passive Fuzzing• More and More Corpus

FuturePlanofOurFuzzingTool

IOKit CodeCoverageExample

macOS <=10.14Root

• Root=CVE-2018-4413+CVE-2018-4425+mach-portal

• mach_portal: alldetailshttps://bugs.chromium.org/p/project-zero/issues/detail?id=1417

• Demo(10.13.6)

• follow me on twitter: @panicaII

MoreInformation

• Google Project Syzkaller1

Acknowledge

ANYQUESTIONS?