Advanced Mac OS X Rootkits
-
Upload
truongquynh -
Category
Documents
-
view
235 -
download
2
Transcript of Advanced Mac OS X Rootkits
Advanced Mac OS X Rootkits
Dino Dai Zovi Chief Scientist
Endgame Systems
2
Overview
• MacOSXandMach
• WhyuseMachforrootkits?
• User‐modeMachrootkittechniques• KernelMachrootkittechniques
2
3
Why Mach Rootkits?
• Tradi>onalUnixrootkittechniquesarewellunderstood
• Machfunc>onalityismoreobscure• Rootkitsusingobscurefunc>onalityarelesslikelytobedetectedorno>ced
• Machisfuntoprogram
3
4
Introduction to Mach
• MacOSXkernel(xnu)isahybridbetweenMach3.0andFreeBSD
• FreeBSDkerneltop‐halfrunsonMachkernelboNom‐half
• Mul>plesystemcallinterfaces:BSD(posi>venumbers),Mach(nega>ve)
• BSDsysctls,ioctls• Machin‐kernelRPCservers,IOKituserclients,etc.
• Machinter‐processcommunica>on(IPC)
• Communicatesoveruni‐direc>onalports,accesscontrolledviarights
• Mul>pletasksmayholdportsendrights,onlyonemayholdreceiverights
4
5
Tasks and Processes
• MachTasksownThreads,Ports,andVirtualMemory
• BSDProcessesownfiledescriptors,etc.• BSDProcesses<=>MachTask
• task_for_pid(),pid_for_task()• POSIXThread!=MachThread
• Libraryfunc>onsuseTLS
5
6
Mach Task/Thread System Calls
• task_create(parent_task,ledgers,ledgers_count,inherit_memory,*child_task)
• thread_create(parent_task,*child_ac>va>on)• vm_allocate(task,*address,size,flags)
• vm_deallocate(task,address,size)
• vm_read(task,address,size,*data)
• vm_write(task,address,data,data_count)
6
7
User-mode Mach Rootkits
• Notas“sexy”askernelmoderootkits
• Canbejustaseffec>veandhardertodetect• Aretypicallyapplica>on/process‐specific• Basedonthreadinjec>onorexecutableinfec>on• Wouldyouno>ceanextrabundleandthreadinyourwebbrowser?
7
8
Injecting Mach Threads
• Getaccesstoanothertask’staskport• task_for_pid()orbyexploi>ngalocalprivilegeescala>onvulnerability
• Allocatememoryinremoteprocessforthreadstackandcodetrampoline
• Createnewmachthreadinremoteprocess
• Executetrampolinewithpreviouslyallocatedthreadstacksegment
• TrampolinecodepromotesMachThreadtoPOSIXThread
• Call_pthread_set_self(pthread_t)andcthread_set_self(pthread_t)
8
9
Mach Exceptions
• TasksandThreadsgenerateexcep>onsonmemoryerrors
• Anotherthread(possiblyinanothertask)mayregisterastheexcep>onhandlerforanotherthreadortask
• Excep>onhandlingprocess:1. AThreadcausesarun>meerror,generatesanexcep>on
2. Excep>onisdeliveredtothreadexcep>onhandler(ifexists)
3. Excep>onisdeliveredtotask’sexcep>onhandler(ifexists)4. Excep>onconvertedtoUnixsignalanddeliveredtoBSDProcess
9
10
Injecting Mach Bundles
• Injectthreadstocallfunc>onsintheremoteprocess
• Remotethreadcallsinjectedtrampolinecodeandthentargetfunc>on
• Func>onreturnstochosenbadaddress,generatesanexcep>on• Injectorhandlesexcep>on,retrievesfunc>onreturnvalue
• Calldlopen(),dlsym(),dlclose()toloadbundlefromdisk
• Injectmemory,callNSCreateObjectFileImageFromMemory(),NSLinkModule()
• Injectedbundlecanhooklibraryfunc>ons,Objec>ve‐Cmethods
10
11
inject-bundle
• inject‐bundle– Injectabundlefromdiskintoarunningprocess
– Usage:inject_bundlepath_to_bundle[pid]• Samplebundles
– test:Printoutputonload/run/unload– isight:TakeapictureusingiSightcamera
– sslspy:LogSSLtrafficsentthroughSecureTransport
– ichat:LogIMsfromwithiniChat
11
12
Hooking and Swizzling
• HookingCfunc>onsisbasicallythesameasonanyotherplaqorm– seeRentzsch’smach_override
• Objec>ve‐Crun>mehashookingbuilt‐in:– method_exchangeImplementa>ons()
– orjustswitchthemethodpointersmanually
– allduetoObj‐C’sdynamicrun>me
– useJRSwizzleforportability
12
13
DEMO
13
14
Rootkitting the Web Browser
• Whatclientsystemdoesn’thavethewebbrowseropenatall>mes?
• Willbeallowedtoconnectto*:80and*:443byhost‐basedfirewalls(i.e.LiNleSnitch)
• Backgroundthreadcanpollaknownsiteforcommandandcontrolinstruc>onsorlookforinstruc>onsinHTMLcontentfromanysite
• Injectedbundlesdonotinvalidatedynamiccodesignatures(usedbyKeychain,etc)
14
15
Kernel Mach Rootkits
• MachsystemcallsallowMachRPCtoin‐kernelserverswhichperformtask,thread,andVMopera>ons
• RPCrou>nesarestoredinthemig_bucketshashtablebysubsystemid+subrou>neid
• AnalogoustosysenttableforUnixsystemcalls
• IncomingMachmessagessenttoakernel‐ownedportaredispatchedthroughmig_buckets
• Wecaninterposeonthesefunc>oncallsorinjectnewRPCserversbymodifyingthishashtable
15
16
Example: inject_subsystem
• int inject_subsystem(const struct mig_subsystem * mig)• {• mach_msg_id_t h, i, r;• // Insert each subroutine into mig_buckets hash table• for (i = mig->start; i < mig->end; i++) {• mig_hash_t* bucket; • h = MIG_HASH(i);• do { bucket = &mig_buckets[h % MAX_MIG_ENTRIES];• } while (mig_buckets[h++ % MAX_MIG_ENTRIES].num != 0 && • h < MIG_HASH(i) + MAX_MIG_ENTRIES);• if (bucket->num == 0) { // We found a free spot• r = mig->start - i;• bucket->num = i;• bucket->routine = mig->routine[r].stub_routine;• if (mig->routine[r].max_reply_msg)• bucket->size = mig->routine[r].max_reply_msg;• else• bucket->size = mig->maxsize;• return 0; • }• }• return -1;• }
16
17
Mach Kernel RPC servers
• In‐kernelMachRPCsubsystemsareenumeratedinthemig_etableandinterfacesarein/usr/include/mach/subsystem.defs– mach_vm,mach_port,mach_host,host_priv,host_security,clock,clock_priv,processor,processor_set,is_iokit,memory_object_name,lock_set,ledger,semaphore,task,thread_act,vm_map,UNDReply,default_pager_object,security
17
18
Machiavelli
• MachRPCprovideshigh‐levelremotecontrol– vm_alloc(),vm_write(),thread_create()onkerneloranytask
• Wanttos>lluseMiGgeneratedclientRPCstubs
• MachiavelliProxyrunsasbackgroundthreadincontrolu>li>esonaNacker’ssystem
• MachiavelliAgentsrunontheremotecompromisedhostasuser‐modeprocessorinkernel
18
19
NetMessage and NetName servers
• NetworktransparencyofIPCwasadesigngoal• OldMachreleasesincludedtheNetMessageServer
– MachserverscouldregisterthemselvesonthelocalNetNameserver
– Clientscouldlookupnamedserversonremotehosts
– LocalNetMessageserverwouldactasaproxy,transmiungMachIPCmessagesoverthenetwork
• ThesefeaturesnolongerexistinMacOSX
19
20
Machiavelli Architecture
• MachiavelliProxy– RunsasbackgroundthreadofaMachiavelliu>lity
– ReceivesmessagesonproxyportsandsendstoremoteAgent
– ReplacesportnamesinmessagesreceivedfromAgentwithproxyports
• MachiavelliAgent– ReceivesmessagesovernetworkfromProxy,sendstorealdes>na>on
– Receivesandtransmitsreplymessageifareplyisexpected
• MachiavelliU>li>es– Runoncontrolhost,useProxytocontrolcompromisedhost
20
21
Mach messages
• Machmessagesarestructuredandunidirec>onal
• Header:• typedef struct• {• mach_msg_bits_t msgh_bits;• mach_msg_size_t msgh_size;• mach_port_t msgh_remote_port;• mach_port_t msgh_local_port;• mach_msg_size_t msgh_reserved;• mach_msg_id_t msgh_id;• } mach_msg_header_t;• Bodyconsistsoftypeddataitems
21
22
Complex Mach Messages
• “Complex”Machmessagescontainout‐of‐linedataandmaytransferportrightsand/ormemorypagestoothertasks
• Inthemessagebody,descriptorsdescribetheportrightsandmemorypagestobetransferred
• Kernelgrantsportrightstothereceivingprocess• Kernelmapstransferredpagestoreceivingprocess,some>mesatmessage‐specifiedaddress
22
23
Proxying Mach Messages
• ProxymaintainsaMachportset– Aportsethasthesameinterfaceasasingleportandcanbeusediden>callyinmach_msg()
– Eachproxyportinthesetcorrespondstotherealdes>na>onportnameintheremoteAgent
– Portnamescanbearbitrary32‐bitvalues,soportsetnamesarepointerstorealdes>na>onportnamevalues
• Receivedmessagesmustbetranslated(local<=>remoteportsanddescriptorbits)
• Messagesareserializedtobytebuffersandthensent
23
24
Serializing Mach Messages
• Serializing“simple”messagesissimpleastheydon’tcontainanyout‐of‐linedata
• Out‐of‐linedataisappendedtotheserializedbufferinorderofthedescriptorsinthebody
• Portnamesaretranslatedduringdeserializa>on– Transla>ngtoanintermediate“virtualportname”mightbecleaner
24
25
Deserializing Mach Messages
• Portnamesinthemachmessagemustbereplacedwithlocalportnames
• OnAgent,thisisdonetoreceivethereply• OnProxy,thisisdonetoreplacetransferredportnameswithproxyportnames– Ensuresthatonlytheini>alportmustbemanuallyobtainedfromtheproxy,therestarehandledautoma>cally
• OOLmemoryismapped+copiedintoaddressspace
25
26
Machiavelli example
• int main(int argc, char* argv[])• {• kern_return_t kr;• mach_port_t port;• vm_size_t page_size;
• machiavelli_t m = machiavelli_init();• machiavelli_connect_tcp(m, "192.168.13.37", "31337");• port = machiavelli_get_port(m, HOST_PORT);• • if ((kr = _host_page_size(port, &page_size)) != KERN_SUCCESS) {• errx(EXIT_FAILURE, "_host_page_size: %s", mach_error_string(kr));• }
• printf("Host page size: %d\n", page_size);• • return 0;• }
26
27
DEMO
27
28
Miscellaneous Agent services
• Agentmustprovideini>alMachports:– hostport– task_for_pid()(ifpid==0=>returnskerneltaskport)
• AsOSXisaMach/Unixhybrid,justcontrollingMachisnotenough– i.e.Howtolistprocesses?
• Insteadofimplemen>ngUnixfunc>onalityinAgent,injectMachRPCservercodeintopid1(launchd)
28
29
Network Kernel Extensions (NKEs)
• NKEscanextendormodifykernelnetworkingfunc>onalityvia:
• Socketfilters• IPfilters• Interfacefilters• Networkinterfaces• Protocolplumbers
29
30
Conclusion
• Machisawholelotoffun
• MachIPCcanbemadenetworktransparentandprovidesagoodabstrac>onforremotehostcontrol
• IwishmydesktopwasassecureasmyiPhone
• Forupdatedslidesandtoolsgoto:– hNp://trailovits.com/
30