12.07.2015 Views

Hacking Leopard: - Black Hat

Hacking Leopard: - Black Hat

Hacking Leopard: - Black Hat

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Hacking</strong> <strong>Leopard</strong>:Tools and Techniques for Attacking the Newest Mac OS XCharlie MillerJake HonoroffIndependent Security Evaluatorscmiller@securityevaluators.comjake@securityevaluators.comJune 22, 2007


started with some of the basics of vulnerabilityanalysis for the newest Mac OS X operatingsystem, <strong>Leopard</strong>.Hacker Friendly FeaturesApple's Mac OS X is touted as the most userfriendly operating system available. This isalso true for security researchers wishing totest the security of the OS. Consider Safari,the default web browser for Mac OS X. Safariwill automatically launch the following applicationswhen it finds corresponding files onthe Internet:• Address Book• Finder• iChat• Script Editor• iTunes• Dictionary• Help Viewer• iCal• Keynote• Mail• iPhoto• QuickTime Player• Sherlock• Terminal• BOMArchiveHelper• Preview• DiskImageMounterThis list was obtained with the RCDefalutAppapplication. Therefore, while these applicationscan not always be given much usersupplied data, a vulnerability in a programsuch as iPhoto, Preview, or QuickTime Playercan be easily extended into a Safari exploit.Additionally, by default, Safari will open filesassociated with these programs (PDF's,MP3's, WAV's, ZIP's, etc) without promptingor warning the user. If that is not enough, bydefault, Safari allows pop-ups, Java, andJavascript, all by default.Another nice thing about Mac OS X is thatsome of the source code is available,http://developer.apple.com/opensource/index.html. This includes most of the standardUnix open source tools, as well as Webkit,the html parsing engine for Safari - more onthis later.Another friendly feature of Mac OS X is that itallows users to do some system configurationthat they normally wouldn't be allowed to do.This includes over fifty setuid root programson a default install of Mac OS X. Most ofthese you would have probably never heardof, including:• Locum• NetCfgTool• afpLoad• TimeZoneSettingTool• securityFixerToolwhile others include familiar files with unfamiliarfile permissions,• netstat• top• psMost of the files in this last group have notbeen setuid root on Linux systems in manyyears.


GotchasWhile Macs have some great developmenttools, they do lack some traditional tools usedin Linux analysis. There are usually equivalenttools available, though, as we’ll see.First, there are differences in naming conventions.In Mac OS X, shared objects, a.k.a.dynamic libraries, have the file extensionDYLIB. Device drivers, a.k.a. kernel modules,have the file extension KEXT. Finally,the Mac OS X applications reside in /Applications,not /bin or /usr/bin. Furthermore, theactual binary will have a pathname of somethinglike/Applications/Preview.app/Contents/MacOS/PreviewProbably the first thing someone with a Linuxbackground will notice when they start to lookat binaries is there is no ldd command. TheMac OS X equivalent command is otool, seebelow.$ otool -L /bin/ls/bin/ls:/usr/lib/libncurses.5.4.dylib (compatibilityversion 5.4.0, current version 5.4.0)/usr/lib/libgcc_s.1.dylib (compatibilityversion 1.0.0, current version 1.0.0)/usr/lib/libSystem.B.dylib (compatibilityversion 1.0.0, current version 88.1.5)Likewise, there is no strace or ltrace. Thecommand to use is ktrace (or dtrace in <strong>Leopard</strong>.More on that in a later section).$ ktrace -tc w...$ kdump4087 ktrace RET ktrace 04 0 8 7 k t r a c e C A L Lexecve(0xbffff3cc,0xbffff990,0xbffff998)Until February 2007, IDA Pro did not supportUniversal Binaries, the type of file used byMac OS X applications. This made disassemblyvery difficult. Luckily, it works now!Another point to remember is that Mac OS Xshellcode has a couple of restrictions. First,you cannot call execve() until you call vfork().Also, despite popular belief, it appears youmust call vfork() instead of fork().One of the biggest bummers regarding MacOS X is that ptrace() is hopelessly broken.For example, it doesn't supportPTRACE_PEEKUSR, PTRACE_GETREGS,etc. This makes writing a ptrace-based debuggerimpossible. Instead, use the MachAPI, the interface into the Darwin kernel.This is how gdb and pydbg both work.The way the heap is handled is different thanin Linux and Windows. This, of course, has alarge impact on heap overflows in this operatingsystem. The Mac OS X heap is composedof zones, which are variable size portionsof virtual memory, and blocks which areallocated within these zones, see “ OS XHeap Exploitation Techniques”. The documentis a must read. However, since 10.4.1,the large zone is no longer located at an addresssmaller than the tiny zone, whichmakes the overall exploitation method discussedin that paper not work as advertised.So unlike most OS’s, there is not a lot ofheap management pointers available on theheap for overwriting. Instead, typically, youneed to overwrite application specific data.One last caveat is that on Mac OS X,LD_PRELOAD is replaced by DYLD_IN-SERT_LIBRARIES. You’ll need this if youwant to use sharefuzz or perform somethingsimilar to Electric Fence.Fuzzing ToolsWith ptrace() broken, what types of fuzzingtools are available for Mac OS X?While the applications and development toolsmentioned throughout this paper were readilyavailable in Mac, there wasn’t much in the


Figure 1: PAIMEIFile fuzz for Mac OS X in actionway of fuzzers. However, this paper introducestwo recent Windows tools, pydbg andPaiMei, that are now available from the Pai-Mei website.pydbg is an open source tool that enables aresearcher to perform a number of useful actions,all from within the Python programinglanguage. For example, pydbg can be usedto monitor a program for exceptions orcrashes, to take memory snapshots of theprocess, or as a general purpose debugger.pydbg was written originally for Windows, butthis tool is now available for Mac OS X in abeta release. Most pydbg features are supported.Using pydbg, it is relatively easy towrite fuzzing and fuzz monitoring tools.Likewise, PaiMei is a reverse engineeringframework, until now only available forWindows. It is built upon pydbg and allowsfor process tracing and file fuzzingwhile recording all data in a back end database.Furthermore, it can output datato graphing programs or to IDA Pro.PaiMei is now available for Mac OS X ina beta release from the PaiMei website.Mac Specific Tools andTechniquesUp to this point, we've discussed various difficultiesfor security researchers using MacOS X and how to get around these problems.However, this is only half the story. There area number of features of Mac OS X that cansignificantly help researchers discover vulnerabilities,especially when fuzzing. Most ofthese are debugging facilities provided tohelp debug end user problems, but securityresearchers can use them as well.Debugging SymbolsThe first is the ability to use debugging symbolsfrom the Mac OS X frameworks. Theselibraries contain extra asserts and produce


verbose output. This output will be on thesystem console if launched through a standardway, i.e. double clicking on it. Alternatively,it will appear in the terminal window iflaunched from within a terminal window.These additional assertions can be used tohelp identify when problems in the applicationarise as early as possible, something nice todo when fuzzing, for example.Core DumpsCore dumps can be useful while fuzzing.They can be enabled globally by editing the/etc/launchd.conf file. Or, within a terminal,they can be enabled by using the ulimit program.Core files generated by the systemcan be found in /cores.Environment VariablesThere are a number of interesting environmentvariables that can be used for memoryallocation.VariableMallocScribbleMallocPre-ScribbleMal-locGuard-EdgesMalloc-CheckHeapMalloc-Check-HeapEachDescriptionIf set, free() sets eachbyte of released memoryto 0x55If set, malloc() sets eachbyte of newly allocatedmemory to 0xAAIf set, adds guard pagesbefore and after largememory allocations.The number of allocationsuntil malloc() beginsvalidating the heap.The number of allocationsbetween heap validations.Setting these environment variables can beextremely useful during fuzzing. The mainbenefit they provide is quickly identifying inputsthat have corrupted memory. A coupleof common problems when fuzzing is that theheap may become corrupt, but unless theapplication uses the corrupted memory, it willnot crash. This makes finding off-by-one errorsespecially difficult. Another problem is aprogram that crashes well after the memorycorruption occurs. This makes finding thevulnerability time consuming and difficult.These environment variables can help alleviatethese problems.For example, you can have malloc() checkthe heap integrity every so many allocations.Additionally, using MallocScribble will helpdetect double free situations when they arise.Using MallocGuardEdges is similar to usingElectric Fence for Linux and will identifybuffer overflows when they occur. Usingthese variables helps make fuzzing more efficientand effective.Another tool, which is similar to the MallocGuardEdgesenvironment variable is theGuarded Memory Allocator, libgmalloc. Thisis analogous to Electric Fence and is startedin a similar fashion,DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylibTextEditCommand Line ToolsThere are a number of tools available thatcan be used to monitor applications, similarto the suite of tools available from sysinternalsfor Windows. Below are some of themost useful,fs_usage: Records file system access for agiven process. Similar to a non-GUI filemon.sc_usage: Records system call informationfor a given process.INIT_ProcessesIf set, delay launch of applicationsby 15 seconds.vmmap: Dumps virtual memory for a process.heap: Gives information about the heap of aprocess


malloc_history: A tool that can either monitorall memory allocation/deallocation or can logmemory allocated/deallocated at a specifiedaddress.lsof: The standard UNIX tool.Using these tools, information can be gainedfrom a running process that can help identifyfiles being used as well as observing howmemory is being used.CrashReporterMuch of the fuzzing literature discusses theneed to attach a debugger to the target applicationin order to monitor when it crashes. Infact, tools like SPIKE, PaiMei, and FileFuzzall do exactly this for their various platforms.Apple was kind enough to let us not worryabout such things, thanks to CrashReporter.Figure 2: Standard CrashReporter dialogueWhen an application crashes, CrashReporterwill record the crash in the system log(/var/log/system.log) and put details of thec r a s h i n t h e c r a s h l o g(/Library/Logs/CrashReporter/.crash.log). This crash log includes theapplication name, pid, exception information,context information, and a backtrace. If it is aGUI application, it presents you with a dialogbox like in Figure 2.Crashreporter can be configured usingCrashReporterPrefs application to allow theoption to attach to the process with GDB afterit crashes, see Figure 3. Also, note that thiswill run the commands from your .gdbinit file,too.Figure 3: Developer information incorporatedinto CrashReporterSource CodeHaving source code can make analysis easierwhen it is available. For example, applicationscan be rebuilt with debugging symbolsor instrumented to provide code coverage.For Mac OS X, source code is available forthe kernel, any open source software included,and WebKit, the HTML engine usedin various applications, including Safari, Mail,and Dashboard.For example, to build WebKit to report codecoverage information, simply add the -coverageflag,Figure 4: CrashReporter with a debugversion of WebKit.


Figure 5: LCOV generated code coverage information for WebKit.-cov-WebKit/WebKitTools/Scripts/build-webkiterageAfter fuzzing Safari or any other WebKit enabledapplication, code coverage can beviewed using lcov, or a similar package, seeFigure 5.Also, don’t symbols make the crash reportedearlier much nicer to read (see Figure 4)?Let Robots Do the WorkAnother great way to fuzz is using theAutomator application. This application allowsyou to perform repetitive actions automatically,exactly what we want for fuzzing!There are many built-in actions that can beused in order to piece together somethinguseful. Additionally, arbitrary Applescript canbe executed. Most Mac OS X applicationshave embedded code that allows Applescriptto access almost any part of the applicationfor automation, i.e. menu selection, buttonpresses, etc.For a simple example, we’ll build a Previewfuzzer. Simply start automator, drag a fewactions into the workflow,


• Ask for Finder Itemsslowdown to the application or operating system.What can security researchers use Dtracefor? One of the first things that a researcherneeds to known when assessing an applicationfor potential vulnerabilities is what codeis executed. The application may consist of abinary and numerous libraries. Using Dtrace,the researcher can quickly identify the componentsthat are affected by user controlledinput and can get code coverage or instructionstraces with little difficulty. It is also possibleto monitor applications access to filesystem, network, or other resources.Figure 6: The workflow for a simple Previewfuzzer• Open Images in Preview• Move to TrashAfter this, select File->Save As and chooseApplication. Next, create a bunch of fuzzedfiles that Preview will read. Finally, launchthe fuzzer you built, select the files, and letthe thing run!DtraceOne of the most exciting additions to be introducedin <strong>Leopard</strong> is the inclusion ofDtrace, originally for Solaris. Dtrace is a dynamictracing mechanism built directly intothe kernel and many of the applications.Dtrace uses the language D, a subset of thecommon C programming language. Programs,or traces, can be written that can beused to dynamically instrument any applicationrunning on Mac OS X.Dtrace works because the operating systemhas a set of probes located throughout thekernel. Dtrace can bind an action to each ofthese probes. As each probe fires, the datais returned to Dtrace for reporting. Best ofall, Dtrace is designed such that inactiveprobes or probes that are not firing cause noA set of simple Dtrace programs is providedin the Appendix. The first one emulates thewindows program Filemon by monitoring andrecording access to the open, close, read,and write system calls. The next sampleprogram is analogous to the Sharefuzz environmentvariable fuzzer. It simply returnslong strings when programs attempt to callgetenv(). Such a program is literally 3 linesof D. Next, a sample program that behaveslike the ltrace library tracing program is provided.Additionally, a program that can doinstruction traces in a target program isgiven. Such a program could be automaticallyproduced from an IDA Pro plugin. Finally,a Dtrace program is given that recordsand prints code coverage in a target program.<strong>Leopard</strong> also comes with a new applicationcalled Xray. This allows tools, includingDtrace applications, to display their results inreal time using a timeline editor similar to GarageBand.This customizable applicationcould be configured to be a fuzzing controlpanel!ConclusionsAs Mac OS X becomes more prevalent, italso becomes a more obvious target for securityresearchers. However, for a researchercoming from the Windows or Linuxworld, there can be a steep learning curve to


DTrace to be included in Next Mac OS X:http://sun.systemnews.com/articles/102/2/news/16842DTrace User Guidehttp://docs.sun.com/app/docs/doc/819-5488Figure 7: Advertisement for X-ray.find the equivalent tools that they are accustomedto using. By using the tools outlined inthis paper, which include both Mac versionsof well-known tools and some Mac OS X exclusivetools, security researchers can comfortablyfocus their efforts on this platform.ReferencesMac OS X internals: A Systems Approach,Amit Singh, Addison Wesley, 2006Apple - Mac OS X - <strong>Leopard</strong> Sneak Peak:http://www.apple.com/macosx/leopard/Mac OS X Debugging Magic:http://developer.apple.com/technotes/tn2004/tn2124.htmlCrashReporter:http://developer.apple.com/technotes/tn2004/tn2123.htmlAppleScript:http://www.apple.com/macosx/features/applescript/Automator:http://www.apple.com/macosx/features/automator/PaiMei:http://pedram.redhive.com/PaiMei/docs/Abusing Mach on Mac OS X:http://www.uninformed.org/?v=4\&a=3\&t=pdfMacPython OSA Modules:http://www.python.org/doc/2.3.5/mac/scripting.htmlFuzzing Software Tools // iDefense Labs:http://labs.idefense.com/software/fuzzing.php\#more\_spikefileKernel Programming Guide: Mach API Reference:http://developer.apple.com/documentation/Darwin/Conceptual/OS X Heap Exploitation Techniqueshttp://felinemenace.org/papers/p63-0x05_OSX_Heap_Exploitation_Technqiues.txtHack a Mac, get $10,000http://news.com.com/8301-10784_3-9710845-7.htmlSafari for Windows: Released and hacked ina dayhttp://www.infoworld.com/article/07/06/11/Safari-for-Windows-released-and-hacked-in-a-day_1.htmlTrends in Mac Market Sharehttp://arstechnica.com/journals/apple.ars/2007/04/05/trends-in-mac-market-shareWith Windows port, a bug-hunting Safari forApplehttp://www.infoworld.com/article/07/06/12/With-Windows-port-a-bug-hunting-Safari-for-Apple_1.htmlMac OS X PPC Shellcode Trickshttp://uninformed.org/?v=1&a=1&t=pdf


AppendixFilemon in dtrace/** dtrace -qs filemon.d */syscall::open:entry,syscall::open64:entry/pid == $1 /{printf("%s(%s)", probefunc, copyinstr(arg1));}syscall::open64:return,syscall::open:return/pid == $1 /{printf("\t\t = %d\n", arg1);}syscall::read:entry,syscall::write:entry/pid == $1/{printf("%s(%d, %s, %4d)", probefunc, arg0, stringof(copyin(arg1,arg2)),arg2);}syscall::read:return,syscall::write:return/pid == $1/{printf("\t\t = %d\n", arg1);}syscall::close:entry/pid == $1/{printf("%s(%d)\n", probefunc, arg0);}sharefuzz in dtrace/** dtrace -wp `pgrep test` -s sharefuzz.d*/pid$target::getenv:return/execname == "test"/{copyoutstr("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", arg1, 128);}


ltrace in Dtrace/** dtrace -qp `pgrep test` -s ltrace.d*/pid$target:::entry/execname == "test"/{printf("%s", probefunc);}pid$target:::return/execname == "test"/{printf("\t\t=%d\n", arg1);}Instruction tracer in Dtrace/** dtrace -qp `pgrep test` -s trace.d*/pid$target:a.out:foo:*/execname == "test2"/{printf("08%x\n", uregs[R_EIP]);}Code coverage using Dtrace/** dtrace -qp `pgrep test` -s code_coverage.d*/pid$target:a.out:foo:*/execname == "test2"/{@code_coverage[uregs[R_EIP]] = count();}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!