Comments 0

Document transcript

Appl e i OS 4 Securi ty Eval uati onDino A. Dai ZoviPrincipalTrail of Bits LLCVersion: 1.0Trail of BitsTabl e of ContentsASLR1Overview1Assessment3Code Signing4Mandatory Code Signing4Code Signing Enforcement11AppleMobileFileIntegrity11Dynamic Code Signing13Assessment14Sandboxing15Introduction15Application Containers15Sandbox Proﬁles15Assessment22Data Encryption24Overview24Hardware Encryption24Trail of BitsApple iOS Security EvaluationiData Protection API25Filesystem Encryption25iOS Passcodes26Data Protection API Coverage27Assessment29Trail of BitsApple iOS Security EvaluationiiASLROverviewAddress Space Layout Randomization (ASLR) is an important protection that makes the remote exploitation of memorycorruption vulnerabilities signiﬁcantly more difﬁcult. In particular, when it is fully applied, it usually requires that attackersﬁnd and exploit one or more memory disclosure vulnerabilities in order to enable the exploitation of a memory corruptionvulnerability. On many operating systems, however, the implementation of ASLR may be incomplete and attackers canmake often make use of executable or writable memory regions at ﬁxed or predictable locations.ASLR was introduced in iOS 4.3 and there are two levels of completeness of ASLR in iOS 4.3, depending on whether theapplication was compiled with support for Position Independent Executables (PIE). If the application was compiledwithout PIE support, it will run with limited ASLR. Speciﬁcally, the main executable binary (including its code and datasections) and the dynamic linker (dyld) will be loaded at ﬁxed locations. The main thread’s stack will also always begin atthe same location in memory. This is presumably to maintain compatibility with existing iOS applications. If the applicationis compiled with PIE support, then the application will be able to make full use of ASLR and all memory regions will berandomized. In iOS 4.3, all built-in applications are compatible with full ASLR. The table below summarizes whichsegments of memory will be found at randomized locations depending on whether the application was compiled with orwithout PIE support.Memory Region Randomization by Deployment Target VersionPIEExecutableDataHeapStackLibrariesLinkerNoFixedFixedRandomizedper executionFixedRandomizedper device bootFixedYesRandomizedper executionRandomizedper executionRandomizedper execution(more entropy)Randomizedper executionRandomizedper device bootRandomizedper executionTrail of BitsApple iOS Security Evaluation1Observing ASLRIn order to detect which memory regions are loaded at randomized locations and how often that location changes, asmall command-line executable1was written to observe and output a memory address within those regions. Theprogram captures the memory addresses of the executable’s main function, a variable in its initialized data segment, avariable in its uninitialized data segment, a single heap allocation, a variable on the stack, the address of a function in aloaded shared library, and the load address of the dynamic linker (dyld). This program was used to observe memoryaddresses for ﬁve invocations before rebooting the device and gathering data from ﬁve more invocations. This wasperformed for the executable compiled with and without support for Position Independent Executables (PIE). The resultsof these tests are shown in the table below.Observed Memory AddressesMain ExecutableHeapStackLibrariesLinker0x2e880x15ea700x2fdff2c00x36adadd10x2fe000000x2e880x11cc600x2fdff2c00x36adadd10x2fe000000x2e880x14e1900x2fdff2c00x36adadd10x2fe000000x2e880x1458600x2fdff2c00x36adadd10x2fe000000x2e880x1344400x2fdff2c00x36adadd10x2fe00000RebootRebootRebootRebootReboot0x2e880x1749800x2fdff2c00x35e3edd10x2fe000000x2e880x13ca600x2fdff2c00x35e3edd10x2fe000000x2e880x1635400x2fdff2c00x35e3edd10x2fe000000x2e880x1369700x2fdff2c00x35e3edd10x2fe000000x2e880x177e300x2fdff2c00x35e3edd10x2fe00000Compile with -fPIECompile with -fPIECompile with -fPIECompile with -fPIECompile with -fPIE0xd2e480x1cd766600x2fecf2a80x35e3edd10x2fed00000xaae480x1ed689500x2fea72a80x35e3edd10x2fea80000xbbe480x1cd093700x2feb82a80x35e3edd10x2feb90000x46e480x1fd36b800x2fe432a80x35e3edd10x2fe440000xc1e480x1dd819700x2febe2a80x35e3edd10x2febf000RebootRebootRebootRebootReboot0x14e480x1dd266400x2fe112a80x36146dd10x2fe120000x62e480x1dd492400x2fe112a80x36146dd10x2fe600000x9ee480x1d5774900x2fe9b2a80x36146dd10x2fe9c0000xa0e480x1e5061300x2fe9d2a80x36146dd10x2fe9e0000xcde480x1fd1d1300x2feca2a80x36146dd10x2fecb000The memory addresses shown in the table above clearly show which memory regions are randomized and how often forboth non-PIE and PIE executables. It also shows that the amount of entropy in heap memory randomization is greater forPIE executables than for non-PIE executables. In this way, the PIE compatibility of an executable can be used todetermine its level of ASLR compatibility in iOS 4.3: limited or full.Trail of BitsApple iOS Security Evaluation21Included in the supplementary materials as src/aslr/aslr.cThird-Party ApplicationsIn order to determine the prevalence of PIE support in third-party applications, the top ten free applications as of the timeof this writing were downloaded and examined. As summarized in the table below, none of these applications werecompiled with PIE support.PIE Support in Top Ten Free ApplicationsApplicationVersionPost DatePIESongify1.0.1June 29, 2011NoHappy Theme Park1.0June 29, 2011NoCave Bowling1.10June 21, 2011NoMovie-Quiz Lite1.3.2May 31, 2011NoSpotify0.4.14July 6, 2011NoMake-Up Girls1.0July 5, 2011NoRacing Penguin, Flying Free1.2July 6, 2011NoICEE Maker1.01June 28, 2011NoCracked Screen1.0June 24, 2011NoFacebook3.4.3June 29, 2011NoXcode Automatic Deployment TargetIn Xcode, the “iOS Deployment Target” application setting is the lowest version of iOS that the application will run on. Thedefault setting is “Compiler Default”, indicating that Xcode will automatically choose the minimum version of iOS basedon the APIs that are used by the application. This may cause more applications to automatically support PIE if they usean API that is only available in iOS 4.3 or later. More likely, however, is that applications that make use of new APIsintroduced in the upcoming release of iOS 5 will automatically be compiled with PIE support.AssessmentIn order to preserve application compatibility, applications compiled without PIE support do not run with full ASLR on iOS4.3. This leaves both the application and dynamic linker text segments at ﬁxed known locations. The presence of knowncode sequences at known locations facilities the use of code reuse techniques such as return-oriented programming inthe exploitation of memory corruption vulnerabilities. The most likely targets for remote exploits, however, are the built-inMobileSafari and MobileMail applications, which are both compiled with PIE support and make use of full ASLR in iOS4.3.Scriptable applications such as MobileSafari, provide more opportunities for an attacker to identify and exploit memorydisclosure vulnerabilities that may be used to weaken or defeat the randomization provided by ASLR. Other applicationsthat do not provide malicious content as many opportunities to inspect their runtime environment and adapt to it aresigniﬁcantly more difﬁcult to remotely exploit. The presence of full ASLR, especially in combination with the other runtimeprotections described in this document such as Code Signing Enforcement and Sandboxing, makes the remoteexploitation of memory corruption vulnerabilities in iOS applications signiﬁcantly more difﬁcult than on other mobile ordesktop platforms.Trail of BitsApple iOS Security Evaluation3Code Si gni ngMandatory Code SigningIn order to verify the authenticity of all executable code running on the device, iOS requires that all native code(command-line executables and graphical applications) is signed by a known and trusted certiﬁcate. This protection isreferred to as Mandatory Code Signing. The Mandatory Code Signing system also forms the basis of the code signingsecurity model in iOS whereby particular developers or software may be granted speciﬁc additional privileges.There are several important components to the code signing security model:•Developer Certiﬁcates•Provisioning Proﬁles•Signed Applications•EntitlementsWe will describe what these components are and how they interact in turn.Developer CertiﬁcatesAny developer may freely download Apple’s Xcode developer tools and test their applications within the included iOSSimulator. The iOS Simulator runs on the developer’s Mac and allows them to interact with their application by simulatingtouch events and other device hardware features using the mouse and keyboard. While this allows basic developmentand testing, it may not be sufﬁcient for many applications that need to ensure they run fast enough on actual hardware(i.e. games) or interact properly with location-based services, the digital compass, or accelerometer. In order to runcustom applications on an actual iOS device, even just for testing, the developer must be granted a Developer Certiﬁcatefrom Apple by being an approved member of Apple’s iOS Developer Program2.Developers may apply for this program as an individual, company, enterprise, or university. Depending on how thedeveloper applies, they may enroll in either the Standard, Enterprise, or University Programs and they each have separateveriﬁcation requirements and developer privileges, including how and whether developers may distribute theirapplications. An individual or company enrollment for the Standard Program is typically used to publish free or paidapplications on Apple’s App Store. The Enterprise Program is for larger companies and organizations to develop anddistribute custom in-house applications. Finally, the University Program is designed to facilitate educational institutionsteaching iOS development and it only permits on-device testing (no application distribution is permitted).Trail of BitsApple iOS Security Evaluation42

http://developer.apple.com/programs/ios/Developer ProgramDevice TestingAd HocApp StoreIn-HouseApple DeveloperNoNoNoNoUniversity ProgramYesNoNoNoStandard ProgramYesYesYesNoEnterprise ProgramYesYesNoYesAll of the developer programs require veriﬁcation of the individual developer’s or developer organization’s real-worldidentity. For an individual, the use of a credit card to pay for the yearly membership fee is sufﬁcient veriﬁcation. In order toapply as a company, the developer must submit the Articles of Incorporation or Business License. An Enterprise mustsubmit their DUNS Number3and pay a higher yearly membership fee. The University program is only open to qualiﬁed,degree granting, higher education institutions. For the purposes of this paper, we will use the term “developer” to refer toan individual or organizational member of Apple’s iOS Developer Program and only specify which type of developer whenit is signiﬁcant.Provisioning ProﬁlesA Provisioning Proﬁle is an XML plist4ﬁle signed by Apple that conﬁgures the iOS device to permit the execution of codesigned by the embedded developer certiﬁcate. It also lists the entitlements that the developer is permitted to grant toapplications signed by their certiﬁcate. The provisioning proﬁle may also include a list of the Unique Device Identiﬁers(UDIDs) of the devices that the proﬁle may provision. For on-device testing, the provisioning proﬁle will only list thedeveloper’s testing device that they have conﬁgured via the iOS Developer Portal. For Ad-Hoc Distribution, an Ad-HocDistribution Provisioning Proﬁle may list up to 100 devices for wider application testing. Enterprise Provisioning Proﬁlesare signiﬁcantly more powerful since they are not restricted to a list of devices in the provisioning proﬁle.An example Development Provisioning Proﬁle for on-device developer testing is shown in Figure 1. All provisioningproﬁles are stored on the ﬁlesystem in the directory /var/MobileDevice/ProvisioningProﬁles/. The provisioning proﬁlevalidation is performed by the MISProvisioningProﬁleCheckValidity function in /usr/lib/libmis.dylib. If the provisioningproﬁle is properly validated, then it will be displayed in the System Preferences application and usable for verifying signedapplications. In order to be considered valid, all of the following conditions must hold:•The signing certiﬁcate must be issued by the built-in “Apple iPhone Certiﬁcation Authority” certiﬁcate•The signing certiﬁcate must be named “Apple iPhone OS Provisioning Proﬁle Signing”•The certiﬁcate signing chain must be no longer than three links long•The root certiﬁcate (referred to as the “Apple CA”) must have a particular SHA1 hash•The provisioning proﬁle version number must be 1•The provisioning proﬁle must contain the UDID of this device or the proﬁle must contain the key“ProvisionsAllDevices”•The current time is before the expiration date of the proﬁleTrail of BitsApple iOS Security Evaluation53DUNS numbers are issued by Dun and Bradstreet, a business credit reporting ﬁrm4A plist ﬁle is a standard Apple XML ﬁle format for storing property lists (nested key-value pairs)<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>ApplicationIdentifierPrefix</key><array><string>9ZJJSS7EFV</string></array><key>CreationDate</key><date>2010-08-20T02:55:55Z</date><key>DeveloperCertificates</key><array><data>...</data></array><key>Entitlements</key><dict><key>application-identifier</key><string>9ZJJSS7EFV.*</string><key>get-task-allow</key><true/><key>keychain-access-groups</key><array><string>9ZJJSS7EFV.*</string></array></dict><key>ExpirationDate</key><date>2010-11-18T02:55:55Z</date><key>Name</key><string>Development</string><key>ProvisionedDevices</key><array><string>e757cfc725783fa29e8b368d2e193577ec67bc91</string></array><key>TimeToLive</key><integer>90</integer><key>UUID</key><string>BDE2CA16-499D-4827-BB70-73886F52D30D</string><key>Version</key><integer>1</integer></dict></plist>Figure 1: Sample Provisioning ProﬁleSigned ApplicationsAll iOS executable binaries and applications must be signed by a trusted certiﬁcate. While Apple’s certiﬁcates areinherently trusted, any other certiﬁcates must be installed via a properly signed Provisioning Proﬁle, as described above.Command-line executables may contain either an ad-hoc signature, as shown for an iOS binary in Figure 2 or atraditional signature as shown for a Mac OS X built-in executable in Figure 3.Trail of BitsApple iOS Security Evaluation6% codesign -dvvv debugserverExecutable=/Developer/usr/bin/debugserverIdentifier=com.apple.debugserverFormat=Mach-O universal (armv6 armv7)CodeDirectory v=20100 size=1070 flags=0x2(adhoc) hashes=45+5 location=embeddedCDHash=6a2a1549829f4bff9797a69a1e483951721ebcbdSignature=adhocInfo.plist=not boundSealed Resources=noneInternal requirements count=1 size=152Figure 2: Ad-hoc code signed executable% codesign -dvvv iBooksExecutable=/.../9D3A8D85-7EDE-417A-9221-1482D60A40B7/iBooks.app/iBooksIdentifier=com.apple.iBooksFormat=bundle with Mach-O universal (armv6 armv7)CodeDirectory v=20100 size=14585 flags=0x0(none) hashes=721+5 location=embeddedHash type=sha1 size=20CDHash=ac93a95bd6594f04c209fb6bf317d148b99ac4d7Signature size=3582Authority=Apple iPhone OS Application SigningAuthority=Apple iPhone Certification AuthorityAuthority=Apple Root CASigned Time=Jun 7, 2011 11:30:58 AMInfo.plist entries=36Sealed Resources rules=13 files=753Internal requirements count=2 size=344Figure 3: Normal code signed executableAn ad-hoc signature does not contain an actual certiﬁcate and is typically only seen on Apple-supplied command-lineexecutables for iOS. These ad-hoc signatures are validated by searching for its code directory hash (CDHash) in thetrustcache. The kernel contains a static set of known CDHashes for all iOS built-in executables and applications that we referto as thestatic trust cache. The kernel also maintains a linked list of the CDHashes for all applications and executablesthat have the passed full certiﬁcate validation before their ﬁrst execution. We call this data structure thedynamic trustcache.The dynamic trust cache contains all the unique executables or applications that have been executed since boot.There does not appear to be any garbage collection or pruning of this linked list.Trail of BitsApple iOS Security Evaluation7Figure 4: Warning message on ﬁrst launch of a custom applicationThe ﬁrst time that a new custom application (i.e. not one signed by Apple and downloaded from the App Store) is run,iOS will prompt the user whether they are sure that they would like to run the application. The warning box, as shown inFigure 4, displays both the application name and the name of the Developer Certiﬁcate that it is signed with.EntitlementsSigned executable binaries and applications may also contain an XML plist ﬁle specifying a set ofentitlementsto grantthe application. This plist ﬁle contains a dictionary of keys with each representing a special privilege to be granted to theapplication. This mechanism allows Apple to make some processes more privileged than others, even if they are allrunning as the same Unix user id (i.e. user mobile).The entitlements that may be granted to a particular application depend on which entitlements have been granted to thesigning developer’s certiﬁcate in its associated provisioning proﬁle. Since Apple signs every provisioning proﬁle, thisallows them to carefully control which entitlements they will allow other developers to grant to that developer’s customapplications. The provisioning proﬁle shown above in Figure 1 has an entitlements dictionary with three keys: application-identiﬁer, get-task-allow, and keychain-access-groups. The application-identiﬁer entitlement speciﬁes a unique preﬁx forapplications they develop. The Application Identiﬁers in iOS are used to uniquely refer to particular applications. Whilethird-party developers are assigned unique preﬁxes, Apple has reserved com.apple.* for themselves. The get-task-allowentitlement permits applications signed with the embedded developer certiﬁcate to be debugged, indicating that thisprovisioning proﬁle is intended to permit on-device custom application testing. Applications that are built for distribution(ad-hoc, App Store, or in-house) must omit this key in their entitlements as the associated distribution provisioningTrail of BitsApple iOS Security Evaluation8proﬁles will not permit the key to be in applications signed by the certiﬁcate in the proﬁle. The third entitlement, keychain-access-groups, deﬁnes a list of the iOS Keychain namespaces that the developer may permit their applications toaccess. Note that this list is set to only include the developer’s Application Identiﬁer preﬁx. This allows all of their apps toshare iOS Keychain items if the developer wishes. The developer may also subdivide this namespace between theirapplications in order to prevent different applications that they develop from accessing the same items in the iOSKeychain.As another example of how entitlements are speciﬁed, consider the Entitlements plist for the Apple-provided debugserveras shown in Figure 5. This entitlements dictionary contains three entitlements: com.apple.springboard.debugapplications,run-unsigned-code, and seatbelt-proﬁles. The ﬁrst entitlement is an application-speciﬁc entitlement that informsSpringboard that debugserver should be permitted to debug applications. The second entitlement, run-unsigned-code,appears to indicate that the debugserver should be allowed to run unsigned code. This does not appear, however, to besufﬁcient to allow debugserver to run arbitrary unsigned code, as the authorization checks performed byAppleMobileFileIntegrity (described below) to run with an invalid code signature require additional entitlements. Theseatbelt-proﬁles entitlement lists which built-in sandbox proﬁle to apply to the process (the iOS sandbox is described indetail in a later chapter).<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>com.apple.springboard.debugapplications</key><true/><key>run-unsigned-code</key><true/><key>seatbelt-profiles</key><array><string>debugserver</string></array></dict></plist>Figure 5: Entitlements plist for debugserverApplication Distribution ModelsDevice TestingThe simplest form of application distribution is on-device testing using a Development Provisioning Proﬁle. TheDevelopment Provisioning Proﬁle created for the developer through the iOS Developer Portal or automatically by Xcodeprovisions a single device to run software signed by that developer’s certiﬁcate. This provisioning proﬁle must be installedonto the device before any of the developer’s applications will run on it. The ﬁrst time that a particular custom applicationis run using the developer’s certiﬁcate, the user will be warned with the dialog box shown in Figure 4. This model isintended to allow the developer to continually test their applications on their devices as they are developing them.Ad-Hoc DistributionIn the later stages of testing, the developer may wish to beta test their application on a wider range of devices and by awider range of users. The ad-hoc distribution model is designed for this scenario and allows a developer to distributetheir application for testing to up to 100 users. This distribution model requires that the developer create a separate Ad-Hoc Provisioning Proﬁle. In order to do so, the developer must collect the UDIDs from all of their testers devices. Thedeveloper must then enter these UDIDs into the iOS Developer Portal and create an Ad-Hoc Provisioning Proﬁle thatTrail of BitsApple iOS Security Evaluation9includes all of them in the ProvisionedDevices array. Finally, the developer must send each tester the provisioning proﬁleand an iOS application as an .ipa ﬁle signed with the developer’s Distribution Certiﬁcate. The testers may then drag bothof these ﬁles into iTunes in order to install the application on their device.App Store DistributionIn order to submit an application to Apple’s App Store, the developer must build the application for distribution and sign itwith their Distribution Certiﬁcate. They may then upload it through iTunes Connect for Apple’s review. After the applicationis approved, Apple will re-sign the application with an Apple signing certiﬁcate and make the application available fordownload on the App Store. Since the application is now signed with an Apple certiﬁcate, users do not need to install theoriginal developer’s provisioning proﬁle in order to run the application.In-House DistributionEnterprise developers may take advantage of a special distribution model that bypasses Apple’s App Store reviewprocess and permits installation of the applications on devices without conﬁguring their UDIDs in the provisioning proﬁle.This model, In-House Distribution, is designed for large organizations to distribute their own custom applications to theiremployees.The Enterprise Provisioning Proﬁle may be preloaded on users’ devices when they install their organization’s iOSConﬁguration Proﬁle or conﬁgure their device to use their organization’s Mobile Device Management (MDM) server.Alternatively, the provisioning proﬁle may be installed manually just as is done with Ad-Hoc Distribution. The customapplication may be pushed out to user’s devices through MDM or sent to individual users via Over-the-Air (OTA)Distribution.Over-the-Air (OTA) DistributionOTA Distribution is designed to allow Enterprise Developers to send applications to individual users in their organizationthrough e-mail or by hosting the application on a web server. The link to the application can be sent to the users via e-mail, SMS, or linked to from another web page. Although it was not designed for it, this method can also be used tofacilitate Ad-Hoc Distribution5. This is done by simply packaging up the Ad-Hoc Provisioning Proﬁle with the applicationinstead of an Enterprise Provisioning Proﬁle.While OTA Distribution greatly facilitates sending software to enterprise users and beta testers, it does create a potentialavenue for social-engineering based attacks that may convince users to install undesirable applications. If an attacker isable to obtain an Enterprise Distribution Certiﬁcate (perhaps fraudulently), they may use this to build a maliciousapplication that will not be reviewed by Apple. They can then proceed to attempt to convince users to install thisapplication through SMS, e-mail, or other web pages linking to it.As a partial mitigation against malicious use of this feature, iOS prompts the user before installing the application with“<Developer> would like to install <Application>: Cancel / Install”. If the enterprise organization is a trusted name and theapplication name seems plausible the user will likely install it. The second mitigation against this is Apple’s purposed “kill-switch” that can remove malicious applications from all iOS devices globally6. The exact functioning of this mechanismhas not yet been identiﬁed.Trail of BitsApple iOS Security Evaluation105“Distribute Ad Hoc Applications Over the Air (OTA)”,http://iphonedevelopertips.com/xcode/distribute-ad-hoc-applications-over-the-air-ota.html6“Apple iPhone ‘Kill Switch’ Discovered”,http://www.telegraph.co.uk/technology/3358115/Apple-iPhone-kill-switch-discovered.htmlCode Signing EnforcementIn order to prevent the introduction of new executable code at runtime, iOS implements a security protection called CodeSigning Enforcement (CSE). This prevents applications from loading unsigned libraries, downloading new code atruntime, and using self-modifying code. It is also a strong protection against remote attacks that inject new native codeinto the application (i.e. classic buffer overﬂow and many other memory corruption attacks). It is, however, signiﬁcantlystronger than protections such as Data Execution Prevention (DEP) found on Microsoft Windows and non-executablememory protections found on other operating systems. With these systems, an attacker can repurpose already loadedapplication code in order to enable the execution of an injected native code payload. With iOS CSE, the attacker mustuse already-loaded code in order to achieve all of their objectives, signiﬁcantly raising the cost of attack development.CSE is built into the iOS kernel’s virtual memory system and most of its implementation is visible in Apple’s open sourcexnu kernel7, which is shared between iOS and Mac OS X. In essence, the virtual memory system tracks the validity ofexecutable memory pages and the process as a whole using the “dirty” bit used to implement Copy-on-Write (COW)semantics and virtual memory page-ins. When an executable memory page is paged-in and is marked as being “dirty”,its signature may have been invalidated and it must be reveriﬁed. New executable memory pages are always “dirty”. If asingle memory page is found to be invalid, then the entire process’ code signing validity is also set to be invalid.The code signing validity of the process is tracked with the CS_VALID ﬂag in the csﬂags member of the kernel’s procstructure for that process. If the executable’s code signing signature has been validated prior to it being executed, theprocess begins execution with the CS_VALID ﬂag set. If the process becomes invalid, then this ﬂag will be cleared. Whathappens next depends on the CS_KILL ﬂag. If this ﬂag is set, the kernel will forcibly kill the process once it becomesinvalid. On Mac OS X, the default is to not set this ﬂag so that processes created from signed binaries may becomeinvalid. On iOS, however, this ﬂag is set by default so the process is killed once it becomes invalid. The ﬂags deﬁned forthis ﬁeld and a system call (csops) for getting and setting them from user space are documented in bsd/sys/codesign.h.The deﬁned ﬂags are also summarized in the table below:Flag NameValueDescriptionCS_VALID0x00001Process is dynamically validCS_HARD0x00100Process shouldn’t load invalid pagesCS_KILL0x00200Process should be killed if it becomes dynamically invalidCS_EXEC_SET_HARD0x01000Process should set CS_HARD on any exec’d childCS_EXEC_SET_KILL0x02000Process should set CS_KILL on any exec’d childCS_KILLED0x10000The process was killed by the kernel for being dynamically invalidAppleMobileFileIntegrityThe AppleMobileFileIntegrity kernel extension uses the Mandatory Access Control Framework (MACF) to implement thesecurity protections related to Code Signing. It does so by installing MAC policy hook functions to check the signatureson executed binaries, set default code signing-related process ﬂags, and add extra authorization checks to thetask_for_pid, execve, and mmap system calls.For each function, a summary of its purpose and usage by AMFI are given in the table below (the MAC label lifecyclemanagement functions have been omitted for brevity).Trail of BitsApple iOS Security Evaluation117

http://www.opensource.apple.com/source/xnu/AppleMobileFileIntegrity MAC Policy HooksMAC Policy HookAPI DescriptionAMFI Usagempo_vnode_check_signatureDetermine whether the given codesignature or code directory SHA1hash are valid.Checks for the given CDHash in thestatic and dynamic trust caches. If it isnot found, the full signature isvalidated by performing an RPC call tothe userspace amﬁd daemon. If aparticular global ﬂag is set(amﬁ_get_out_of_my_way), then anysignature is allowed.mpo_vnode_check_execDetermine whether the subjectidentiﬁed by the credential canexecute the passed vnode.Sets the code signing CS_HARD andCS_KILL ﬂags, indicating that theprocess shouldn’t load invalid pagesand that the process should be killed ifit becomes invalid.mpo_proc_check_get_taskDetermine whether the subjectidentiﬁed by the credential can get thepassed process's task control port.Allows task port access if the targetprocess has the get-task-allowentitlement and the calling task hasthe task_for_pid-allow entitlement.mpo_proc_check_run_cs_invalidDetermine whether the process mayexecute even though the systemdetermined that it is untrusted(unidentiﬁed or modiﬁed code)Allow execution if the process has theget-task-allow, run-invalid-allow, orrun-unsigned-code entitlements or anRPC call to amﬁd returns indicatingthat unrestricted debugging should beallowed.mpo_proc_check_map_anonDetermine whether the subjectidentiﬁed by the credential should beallowed to obtain anonymousmemory with the speciﬁed ﬂags andprotections.Allows the process to allocateanonymous memory if and only if theprocess has the dynamic-codesigningentitlement.mpo_cred_check_label_update_execveIndicate desire to change the processlabel at exec timeReturns true (non-zero) to indicate thatAMFI needs to update credentials atexec time.mpo_cred_label_update_execveUpdate credential at exec timeUpdates the credential with theentitlements of the newly executedbinary or Application.Trail of BitsApple iOS Security Evaluation12In order to implement some more expensive operations outside of the kernel, the AMFI kernel extension communicateswith a userspace daemon, amﬁd, over Mach RPC. The amﬁd RPC interface is simply two routines, as shown in the tablebelow.AMFI Daemon Mach RPC InterfaceMessage IDSubroutineDescription1000verify_code_directoryVeriﬁes the given code directory hash and signature for theexecutable at the given path. This checks whether the signatureis valid and that it should be trusted based on the built-in Applecertiﬁcates and installed provisioning proﬁles (if any).1001permit_unrestricted_debuggingEnumerates the installed provisioning proﬁles and checks for aspecial Apple-internal provisioning proﬁle with the UDID of thecurrent device that enables unrestricted debugging on it.Signature ValidationThe AppleMobileFileIntegrity mpo_vnode_check_signature MAC hook is responsible for determining whether thesignature on a given executable should be trusted or not. The hook determines this by consulting the static and dynamictrust caches, a most-recently-used (MRU) trust cache, and the amﬁd daemon. The process for doing so is depicted inthe ﬂow chart in Figure 6.vnode_check_signatureIs CDHash in statictrust cache?Is CDHash indynamic trust cache?Is CDHash in MRUtrust cache?Move CDHashentry to front ofMRU linked listAdd CDHashentry to front ofMRU linked listNoYesNoRPC call to amﬁdverify_code_directoryFailureYesSuccessIsamﬁ_get_out_of_my_way true?Isamﬁ_allow_any_signaturetrue?NoDenyAllowYesNoYesYesNoFigure 6: Flow chart of vnode_check_signatureDynamic Code SigningIn order to support the “Nitro” native Just-in-Time (JIT) compilation JavaScript engine, MobileSafari possesses thedynamic-codesigning entitlement. This allows it to loosen the default Code Signing Enforcement mechanism and allow itTrail of BitsApple iOS Security Evaluation13to generate native executable code at runtime. Without this entitlement, the MobileSafari process would not be permittedto create new executable memory pages. On iOS 4.2 and earlier, MobileSafari was restricted to using an interpretedbytecode JIT JavaScript engine, which has much poorer performance than a native code JIT. With the release of iOS 4.3,however, MobileSafari began using the Nitro native code JavaScript JIT engine for increased performance.AssessmentThe Mandatory Code Signing and Code Signing Enforcement security protections are a stronger defense against theexecution of unauthorized native code than the protections found on other common desktop and mobile operatingsystems. In particular, the runtime Code Signing Enforcement mechanism is a unique feature that is not found on theseother systems. It is a signiﬁcantly stronger protection against the execution of injected native code than Microsoft’s DataExecution Prevention (DEP) and similar non-executable data memory protections in Linux and Mac OS X. In addition,these desktop operating systems do not have any similar features to Mandatory Code Signing and, by design, permit theexecution of unsigned binaries and applications. Code Signing Enforcement makes remotely executing native code oniOS signiﬁcantly more difﬁcult than on desktop operating systems and Mandatory Code Signing similarly makes installingunauthorized software on iOS-based devices signiﬁcantly more difﬁcult than doing so on a desktop operating system.While Google’s Android and RIM’s BlackBerry OS mobile operating systems implement similar features to the MandatoryCode Signing found in iOS, neither of them implement any non-executable data memory protections. Again, this makesremote injection and execution of native code easier on these platforms than on Apple’s iOS. In addition, it should benoted that all three platforms include mobile web browsers based on the same open-source WebKit HTML renderingengine. This means that all three platforms will likely be affected by any vulnerabilities identiﬁed in this component and, infact, many such vulnerabilities have been identiﬁed over the last several years8.With iOS 4.3 and presumably later versions, the dynamic-codesigning entitlement in MobileSafari that is required topermit native code JavaScript JIT compilation also allows remote browser-based exploits to inject and execute nativecode. On previous versions of iOS and within applications that do not posses this entitlement, an attacker may onlyrepurpose already-loaded native code in their attack. While this has been shown to be Turing-complete and thereforeequivalent to arbitrary native code execution9, it is signiﬁcantly more work and not as reusable across target versions orapplications as native code. In addition, the introduction of Address Space Layout Randomization in iOS 4.3 signiﬁcantlycomplicates code-reuse attacks as well as any taking advantage of Dynamic Code Signing by requiring the attacker toalso discover and exploit a memory disclosure vulnerability.Trail of BitsApple iOS Security Evaluation148

http://osvdb.org/search?search%5Bvuln_title%5D=WebKit9Shacham, Hovav. “The Geometry of Innocent Flesh on the Bone”, Proceedings of CCS 2007, ACM Press.Sandboxi ngIntroductionThe iOS application-based security model requires that applications and their data are isolated from other applications.The iOS Sandbox is designed to enforce this application separation as well as protect the underlying operating systemfrom modiﬁcation by a potentially malicious application. It does so by assigning each installed application a private area ofthe ﬁlesystem for its own storage and applying ﬁne-grained process-level runtime security policies. These securitypolicies enforce ﬁle and system access restrictions on the application.The iOS sandboxing mechanism used for built-in applications, background processes, and third-party applications. Inthis paper, however, we only concern ourselves with the security policy applied to third-party applications in order toassess the risk posed by installing and running potentially malicious third-party applications.Application ContainersThird-party applications on iOS are each assigned their ownApplication Home Directoryorcontaineron the deviceﬁlesystem. These containers are stored within /var/mobile/Applications/UUIDand the Application UUID is randomlygenerated dynamically when the application is installed. If an application is deleted and the re-installed, the old containerwill be deleted entirely and the application will be assigned a brand new random UUID when it is re-installed. In general,the application may only read and write ﬁles within their container, but there are a number of exceptions allowed by theruntime sandbox (described later in this chapter). There are several pre-deﬁned subdirectories within the application’scontainer with the intended purposes described in the table below.Container SubdirectoriesContainer SubdirectoryDescription<AppName>.app/The signed bundle containing the application code and static dataDocuments/Application-speciﬁc user-created data ﬁles that may be shared with the user’s desktopthrough iTunes’s iOS Application “File Sharing” featuresLibrary/Application support ﬁlesLibrary/Preferences/Application-speciﬁc preference ﬁlesLibrary/Caches/Application-speciﬁc data that should persist across successive launches of theapplication, but does not need to be backed uptmp/Temporary ﬁles that do not need to persist across successive launches of the applicationSandbox ProﬁlesSince all applications on iOS run as the same Unix user (mobile), the normal Unix-based security model is not able toprovide sufﬁcient application isolation and system protection. Instead, iOS uses the Sandbox kernel extension to enforceTrail of BitsApple iOS Security Evaluation15more customized security policies. The Sandbox kernel module does this using the MAC Framework to install MACpolicy hooks that apply a ﬁner-grained security policy for accessing system objects and resources. These hooks maketheir access determination by evaluating the per-process security policy (referred to as its “proﬁle”).When an application is launched, its sandbox proﬁle (if any) is determined by the value of its seatbelt-proﬁles entitlement.iOS includes 35 built-in proﬁles usually named for the single application that uses them. For example, the MobileSafariproﬁle is only used by the MobileSafari application. The built-in proﬁles include proﬁles for graphical applications such asMobileSafari, MobileSMS, and MobileMail as well as non-graphical background processes such as apsd, ntpd, and ptpd.The precise internals of Apple’s sandbox implementation have been well documented by other public research10and willonly be covered at a basic level here. Instead we will focus on the sandbox proﬁle applied to third-party applications(called “container”). All of the sandbox proﬁles in iOS have been extracted from the kernel and converted into a morehuman-readable from using Dion Blazakis’ XNUSandbox tools11with some updates and modiﬁcations. These convertedsandbox proﬁles from iOS are included in the supplementary materials.Sandboxed OperationsThe sandboxed system operations are listed in the table beginning on the next page. This list of operations wasextracted from the iOS kernel and the purpose of each is described to the best of our knowledge. The purpose of theoperations were derived from their names, descriptions of similarly named kernel system calls, the xnu kernel sourcecode, and sandbox proﬁle source ﬁles found in Mac OS X.For each operation, the sandbox proﬁle in effect deﬁnes an ordered sequence of rules that are evaluated by the MACpolicy hook installed on that event. The list of sandbox operations is somewhat symmetrical to the list of deﬁned MACpolicy “check” hooks like mpo_ﬁle_check_create, mpo_ﬁle_check_fcntl12, etc. The MAC policy hooks are more speciﬁcthan the list of sandbox operations, so several related MAC policy hooks are often folded into a single sandboxoperation. Unfortunately, many of the iOS-speciﬁc sandbox operations are not documented in the Mac OS X header ﬁlesand use “reserved” members in the mac_policy_ops structure.Each sandbox operation rule may contain a boolean ﬁlter to determine whether the deﬁned result (allow or deny) applies.The ﬁrst rule with a matching ﬁlter determines the result for the requested operation and there is often a ﬁnal default rulewith a ﬁlter that always evaluates to true. These ﬁlter functions are statically deﬁned in the kernel and they perform regularexpression and string matches against resource names or speciﬁc resource type comparisons (i.e. socket type).Trail of BitsApple iOS Security Evaluation1610Blazakis, Dionysus. “The Apple Sandbox”. The BlackHat Brieﬁngs DC 201111

https://github.com/dionthegod/XNUSandbox12See /usr/share/security/mac_policy.hOperationDescriptiondefaultEvaluated if there are no rules deﬁned for the speciﬁc operationappleevent-sendSend an Apple Eventﬁle*Wildcard operation for all deﬁned ﬁle operations belowﬁle-chrootChange the root directory of the current process to the given directoryﬁle-ioctlControl a device through an open device special ﬁleﬁle-issue-extension*Unknownﬁle-issue-extension-readUnknownﬁle-issue-extension-writeUnknownﬁle-mknodMake a special ﬁle node (i.e. device ﬁle)ﬁle-read*Wildcard operation for all ﬁle read operationsﬁle-read-dataRead data from a particular ﬁleﬁle-read-metadataRead the metadata (owner, permissions, size, etc) associated with a ﬁleﬁle-read-xattrRead the extended attributes on a ﬁleﬁle-revokeInvalidate open ﬁle descriptors for the ﬁle at the given pathﬁle-searchSearch a ﬁle system volume quicklyﬁle-write*Wildcard operation for all ﬁle write operationsﬁle-write-createCreate a new ﬁleﬁle-write-dataWrite data to a ﬁleﬁle-write-ﬂagsChange the ﬂags for a ﬁleﬁle-write-modeChange the ﬁle’s permissionsﬁle-write-mountMount a ﬁlesystemﬁle-write-ownerChange the ownership of a ﬁleﬁle-write-setugidSet set-user-id or set-group-id bits on a ﬁleﬁle-write-timesChange the ﬁle’s access timesﬁle-write-unlinkDelete a ﬁleﬁle-write-unmountUnmount a ﬁlesystemﬁle-write-xattrWrite to the ﬁle’s extended attributesiokit*Wildcard operation for IOKit operationsiokit-openOpen a connection to an IOKit User Clientiokit-set-propertiesSet properties on an IOKit objectipc*Wildcard operation for IPC operationsipc-posix*Wildcard operation for POSIX IPCipc-posix-semAccess POSIX semaphoresipc-posix-shmAccess POSIX shared memoryipc-sysv*Wildcard for SysV IPC operationsipc-sysv-msgAccess SysV messagesipc-sysv-semAccess SysV semaphoresipc-sysv-shmAccess SysV shared memoryjob-creationCreate a new job in launchdTrail of BitsApple iOS Security Evaluation17OperationDescriptionmach*Wildcard operation for Mach operationsmach-bootstrapAccess mach bootstrap portmach-lookupLookup a particular Mach RPC server over the bootstrap portmach-priv*Wildcard operation for Mach privileged operationsmach-priv-host-portAccess the Mach host port for the current hostmach-priv-task-portAccess the Mach task port for the current taskmach-task-nameAccess the Mach task name port for the current tasknetwork*Wildcard operation for network operationsnetwork-inboundAccept an inbound network connectionnetwork-bindBind a network or local socketnetwork-outboundEstablish an outbound network connectionpriv*Wildcard operation for privileged operationspriv-adjtimeAdjust the system timepriv-netinet*Wildcard operation for privileged network operationspriv-netinet-reservedportListen for connections on a reserved network port (< 1024)process*Wildcard operation for process operationsprocess-execExecute a binary via execve() or posix_spawn()process-forkCreate a new processsignalSend a Unix signalsysctl*Wildcard operation for sysctl operationssysctl-readRead kernel state variablesysctl-writeWrite kernel state variablesystem*Wildcard operation for system operationssystem-acctEnable or disable process accountingsystem-auditSubmit a BSM audit record to the system audit logsystem-chudAccess the CHUD (Computer Hardware Understanding Development) Tools system callsystem-fsctlControl ﬁlesystemssystem-lcidAccess login contextsystem-mac-labelAccess MAC labelssystem-nfssvcAccess NFS services system callssystem-rebootReboot the systemsystem-schedUnknownsystem-set-timeSet the system timesystem-socketCreate a socketsystem-suspend-resumeSuspend or resume the systemsystem-swapManipulate system swap ﬁles?system-write-bootstrapWrite boot blocks to a disk?mach-per-user-lookupLookup per-user Mach RPC serversTrail of BitsApple iOS Security Evaluation18Container Sandbox ProﬁleThe “container” sandbox proﬁle is the proﬁle that gets applied to all third-party applications. The proﬁle, in general,restricts ﬁle access to the application’s container, some necessary system ﬁles, and the user’s address book. Theapplications are generally allowed to read the user’s media (photos and music), but not write to them. In addition, theapplication is allowed to read and delete ﬁles from the container Documents/Inbox directory, but not write to them. Thereare a few IOKit User Clients that the applications may interact with. All outbound network connections, except forconnecting to launchd’s unix domain sockets, are allowed. Applications are also allowed to execute binaries from withintheir application bundle directory and send signals to themselves. The applications are also allowed to create sockets toreceive kernel events and the system routing table. Finally, the proﬁle does not restrict actions related to POSIXsemaphores, shared memory, ﬁle IOCTLs, Mach bootstrap servers, network socket binding and accepting inboundconnections, certain classes of privileged actions, and reading kernel state information through the kernel sysctl interface.We have made an attempt to simplify and present the sandbox proﬁle without sacriﬁcing any accuracy in the table below.In reading the table, keep in mind that rules are evaluated in order. In that case, the ﬁrst matching rule for a particularoperation will determine the result of the security policy: allow or deny. If there are no rules deﬁned for a particularoperation, the rules for the related operation wildcard may be evaluated instead. If there are no rules for the applicablewildcard operations, then the rules for the “default” operation will be evaluated.Many of the rules use regular expressions to specify applicable resource names. If the rule applies to all resources, wedenote this with a ‘*’ in the table. If the rule only supports matching exact strings, the exact string argument is listedrather than a regular expression representing an exact string match.Trail of BitsApple iOS Security Evaluation19ActionResourceResultdefault*Denyipc-posix-sem*Allowipc-posix-shm*Allowﬁle-ioctl*Allowmach-bootstrap*Allowmach-lookup*Allownetwork**Allownetwork-inbound*Allownetwork-bind*Allowpriv**Allowpriv-adjtime*Allowpriv-netinet**Allowpriv-netinet-reservedport*Allowsysctl-read*Allowﬁle-read*, ﬁle-write*^/private/var/mobile/Library/AddressBook(/|$)Allowﬁle-read*, ﬁle-write*^/private/var/ea/ea([.0-9])+(out|in)$Allowﬁle-read*, ﬁle-write*^/dev/null$Allowﬁle-read*, ﬁle-write*^/dev/dtracehelper$Allowﬁle-read*, ﬁle-write*^/dev/(ttys[0-9][0-9][0-9]|ptmx)$Allowﬁle-read*, ﬁle-write*^/dev/(ptyp[0-9a-f]|ttyp[0-9a-f])$Allowﬁle-read*, ﬁle-write*^/dev/(sha1_0|aes_0)$Allowﬁle-read*, ﬁle-write*^/dev/(urandom|random)$Allowﬁle-read*, ﬁle-write*^/dev/zero$Allowﬁle-read*, ﬁle-write*^/dev/(.)*$Denyﬁle-read*^/System/Library/Carrier Bundles/(.)*.png$Allowﬁle-read*^/private/var/mobile/Library/Carrier Bundles/(.)*/carrier.plist$Allowﬁle-read*^/System/Library/Carrier Bundles/(.)*/carrier.plist$Allowﬁle-read*^/private/var/mobile/Media/iTunes_Control/Artwork($|/)Allowﬁle-read*^/private/var/mobile/Media/iTunes_Control/iTunes($|/)Allowﬁle-read*^/private/var/mobile/Library/ConﬁgurationProﬁles/PublicInfo($|/)Allowﬁle-read*^/private/var/mobile/Library/Preferences/com.apple.carrier.plistAllowﬁle-read*^/private/var/mobile/Library/Carrier Bundles/(.)*.png$Allowﬁle-read*^/private/var/logs(/|$)Denyﬁle-read*^/private/var/mobile/Library/Carrier Bundles($|/)Denyﬁle-read*^/System/Library/Carrier Bundles($|/)Denyﬁle-read*^/private/var/mobile/Media/Photos/Thumbs$Allowﬁle-read*^/private/var/mobile/Library/Caches/MapTiles(/|$)Allowﬁle-read*^/private/var/mobile/Library/Caches/com.apple.IconsCache(/|$)Allowﬁle-read*^/private/var/mobile/Media/Photos/Thumbs/([^/])+.ithmb$)AllowTrail of BitsApple iOS Security Evaluation20ActionResourceResult^/private/var/mobile/Media/Photos/Videos($|/)Deny^/private/var/mobile/Media/Photos/Thumbs($|/)Deny^/private/var/mobile/Media/Photos/com.apple.iPhoto.plist$Deny^/private/var/mobile/Media/com.apple.itdbprep.postprocess.lock$Allow^/private/var/mobile/Media/(PhotoData|Photos|PhotoStreamsData)(/|$)Allow^/private/var/mobile/Media/com.apple.itunes.lock_sync$Allow^/private/var/mobile/Library/Preferences/com.apple.(books|commcenter|itunesstored|springboard|youtube|AppStore|MobileStore).plistDeny^/private/var/mobile/Library/FairPlay(/|$)Deny^/usr/sbin/fairplayd$Deny^/private/var/mobile/Media/Deny^/private/var/mobile/Library/Caches/com.apple.keyboards(/|$)Allow^/private/var/mobile/Library/Preferences(/|$)Allow^/private/var/mobile/Library/Keyboard(/|$)Allow^/private/var/mobile/Library/Deny^/private/var/mobile/Applications/(([-0-9A-Z])*)($|/)Allow^/private/var/mnt/Deny^/private/var/tmp(/|$)Deny^/private/var/mobile/Applications/(.)*$Denyﬁle-write*^/private/var/mobile/Media(/|$)Denyﬁle-write*/private/var/mobile/Library/Preferences/com.apple.Preferences.plist.[0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z]$Allowﬁle-write*^/private/var/mobile/Library/Preferences/com.apple.Preferences.plist$Allowﬁle-write*^/private/var/mobile/Library/Keyboard/Allowﬁle-write*/private/var/mobile/Applications/(([-0-9A-Z])*)/Library/Preferences/.GlobalPreferences.plist$Denyﬁle-write*^/private/var/mobile/Applications/(([-0-9A-Z])*)/Library/Preferences/com.apple.PeoplePicker.plist$Denyﬁle-write*^/private/var/mobile/Applications/(([-0-9A-Z])*)/Documents/Inbox/Denyﬁle-write*^/private/var/mobile/Applications/(([-0-9A-Z])*)/(tmp|Library|Documents)(/|$)Allowﬁle-write*^/private/var/mobile/Applications/(.)*$Denyﬁle-write-unlink^/private/var/mobile/Applications/(([-0-9A-Z])*)/Documents/Inbox/Allowiokit-openAppleKeyStoreUserClientAllowiokit-openAppleMBXSharedAllowiokit-openIMGSGXShared_A0Allowiokit-openIMGSGXGLContextAllowiokit-openIMGSGXDeviceAllowiokit-openIOMobileFramebufferUserClientAllowiokit-openIOSurfaceRootUserClientAllowTrail of BitsApple iOS Security Evaluation21ActionResourceResultIOSurfaceSendRightIMGSGXSharedIMGSGXGLContext_A0AppleJPEGDriverUserClientAppleM2ScalerCSCDriverUserClientAppleMBXDeviceAppleMBXUserClientnetwork-outbound^/private/tmp/launchd-([0-9])+.([^/])+/sock$Denynetwork-outbound^/private/var/tmp/launchd/sock$Denyprocess-exec^/private/var/mobile/Applications/(([-0-9A-Z])*)/([^/])*.app($|/)AllowsignalselfAllowsystem-socketPF_SYSTEM, SYSPROTO_CONTROLAllowPF_SYSTEMAllowPF_ROUTEAllow*DenyAssessmentThe sandbox proﬁles for third-party applications and applications that handle potentially untrusted data (MobileSafari andMobileMail) enforce tight restrictions on which ﬁles the applications may read or write. Very little sensitive data on thedevice is directly accessible on the ﬁlesystem from within the sandbox. The most sensitive ﬁles on the ﬁlesystem that areaccessible through the sandbox are the SQLite ﬁle containing the user’s address book contacts, the user’s photo library,and iTunes library.The container proﬁle allows unrestricted access to local Mach RPC servers over the bootstrap port. There are currently141 accessible bootstrap services, each providing an interface of one or more subroutines. These local RPC servers areused to implement a number of features, but documenting each one and all of their interfaces is a signiﬁcant task andbeyond the scope of this paper. The large number of Mach RPC services accessible from within the sandbox is arelatively large attack surface. If an attacker is able to exploit a memory corruption vulnerability in the implementation ofany of these RPC interfaces, they may be able to inject a return-oriented payload into a process with a less restrictivesandbox environment or a process running without a sandbox. While the locations of most memory segments in theremote service process will be different than in the current process due to ASLR, the memory locations of the systemlibraries will be the same. This may aid the attacker in constructing their exploit and return-oriented payload. This is still asigniﬁcantly more complex attack than exploiting a memory corruption vulnerability in the iOS kernel or an accessibleIOKit User Client. The more likely risk is that these RPC interfaces may contain insufﬁcient authorization checks and thismay allow malicious third-party applications to perform undesirable actions on the user’s device.The most likely attack surface to be used in a sandbox escape is the iOS kernel, including the IOKit User Clients that areallowed by the sandbox proﬁle. In fact, IOKit User Client vulnerabilities were exploited by both JailbreakMe 2.013

(IOSurface) and JailbreakMe 3.0 (IOMobileFramebuffer) in order to escape the MobileSafari sandbox. The kernelinterfaces accessible from within the sandbox are likely to remain the most attractive target for a sandbox escape due tothe fully unrestricted privileges yielded by obtaining kernel code execution.Trail of BitsApple iOS Security Evaluation2213

https://github.com/comex/star/Finally, most other system-level actions are well restricted. Applications cannot use the fork system call to create abackground process, but they can use posix_spawn to execute a binary from their application bundle directory. Any suchbinary, however, is part of the signed application bundle and cannot be written to at runtime (this is prevented by thesandbox proﬁle).Trail of BitsApple iOS Security Evaluation23Data Encrypti onOverviewMobile devices face an increased risk of sensitive data compromise through a lost or stolen device than is faced bytraditional desktop workstations. While traditional workstations and laptops may be protected by Full Disk Encryptionwith pre-boot authentication, most mobile platforms cannot perform any pre-boot authentication. The data encryptionfacilities provided by the mobile platform, if any, are only available after the device has booted up. The limited data inputpossibilities on a touch screen or mobile device keyboard also make entering long passphrases infeasible. All of thismakes data protection on mobile devices more challenging.Apple’s iOS 4 uses a system called Data Protection in order to protect the user’s sensitive data in ﬁles on the ﬁlesystemand items in the Keychain. Data Protection uses the user’s passcode and device-speciﬁc hardware encryption keys toderive encryption keys for designated protected data. This is done in order to hamper an attacker’s efforts to recover theprotected data from a lost or stolen device.The iOS Data Protection internals were documented in precise detail by researchers at Sogeti and presented at the Hackin the Box Amsterdam conference in May 201114. Since it has been publicly described in detail elsewhere, this chapterwill only provide an overview of the data encryption facilities and limitations in iOS. In particular, users should be aware ofthe currently very limited coverage of the Data Protection API and the ease with which the default simple four-digitpasscodes can be guessed on a lost or stolen device.Hardware EncryptionThe iPhone 3GS and later devices include a hardware AES cryptographic accelerator. This crypto accelerator is used forrealtime ﬁlesystem encryption and various other encryption tasks by iOS. In addition to providing high-performance dataencryption and decryption capabilities, it also provides many security services through its use of hardware-protected AESkeys.The AES accelerator includes both a unique per-device key (referred to as the UID Key) and a globally shared key(referred to as the GID Key) that are not accessible to the CPU. They may only be used for encryption or decryptionthrough the AES accelerator itself. The GID Key is primarily used to decrypt iOS ﬁrmware images provided by Apple. TheUID Key is used to derive a number of device-speciﬁc AES keys that are used to encrypt the ﬁlesystem metadata, ﬁles,and Keychain items.Trail of BitsApple iOS Security Evaluation2414“iPhone Data Protection in Depth”,http://esec-lab.sogeti.com/dotclear/public/publications/11-hitbamsterdam-iphonedataprotection.pdfData Protection APIThe Data Protection API is designed to let applications declare when ﬁles on the ﬁlesystem and items in the keychainshould be decrypted and made accessible by passing newly deﬁnedprotection classﬂags to existing APIs. Theprotection class instructs the underlying system when to automatically decrypt the indicated ﬁle or keychain item.In order to use enable Data Protection for ﬁles, the application must set a value for the NSFileProtectionKey attributeusing the NSFileManager class. The supported values and what they indicate are described in the table below. Bydefault, all ﬁles have the protection class NSFileProtectionNone, indicating that they may be read or written at any time.File Protection ClassesProtection ClassDescriptionNSFileProtectionNoneThe ﬁle does not need to be protected and can be read from or written to at any timeNSFileProtectionCompleteThe ﬁle is to be encrypted using a key derived, in part, from the user’s passcode andshould only be made available for reading and writing while the device is unlocked.The protection class of items in the Keychain are similarly indicated by specifying the protection class to the SecItemAddor SecItemUpdate functions. Compared with ﬁles where the protection is either non-existent or complete, the Keychainitem protection classes offer somewhat more control. Keychain items can be accessible at any time, after the device hasbeen ﬁrst unlocked after boot, or anytime that the device is unlocked. In addition, the application may specify whetherthe Keychain item can be migrated onto other devices or not. If one of the “ThisDeviceOnly” protection classes are used,then the Keychain item will be encrypted with a key derived from the Device Key. This ensures that only the device thatcreated the Keychain item can decrypt it. By default, all Keychain items are created with a protection class ofkSecAttrAccessibleAlways, indicating that they can be decrypted at any time and migrated onto other devices.Keychain Item Protection ClassesProtection ClassDescriptionkSecAttrAccessibleAlwaysThe keychain item is accessible at any timekSecAttrAccessibleAfterFirstUnlockThe keychain item may be accessed anytime after thedevice is unlocked for the ﬁrst time after being poweredon.kSecAttrAccessibleWhenUnlockedThe keychain item may only be accessed while the deviceis unlocked.kSecAttrAccessibleAlwaysThisDeviceOnlyThe keychain item is accessible at any time, but it maynot be migrated onto another device.kSecAttrAccessibleAfterFirstUnlockThisDeviceOnlyThe keychain item may be accessed anytime after thedevice is unlocked for the ﬁrst time after being poweredon and may not be migrated onto another device.kSecAttrAccessibleWhenUnlockedThisDeviceOnlyThe keychain item may be accessed while the device isunlocked and may not be migrated onto another device.Filesystem EncryptionThe iPhone 3GS and later devices use the embedded encryption accelerators to perform block-level encryption on boththe System and Data partitions. This is primarily to support a quick remote wipe operation. On earlier versions of iOS, theremote wipe command would force the device to overwrite each block of the ﬂash storage, which could take hours toTrail of BitsApple iOS Security Evaluation25complete. Now, the entire ﬁlesystem can be rendered unreadable by simply wiping a single encryption key (referred tohere as the File System Key).This level of ﬁlesystem encryption does not prevent the recovery of data from a lost device. If the remote wipe commandis not received, an attacker may boot the device using a custom RAM disk and use the device itself to decrypt theencrypted partitions. This was demonstrated against the iPhone 3GS running iOS 3 by using iPhone jailbreak utilities toexploit the Boot ROM and boot a custom RAM disk enabling remote SSH access to the device15. This same style ofattack can be used against iOS 4, but it will only give access to the ﬁlesystem metadata (directory structure, ﬁle names,permissions, owners, ﬁle sizes, etc) and ﬁles protected using the NSProtectionNone protection class.If the raw ﬁlesystem is forensically copied off the device by directly accessing the device ﬁle, however, only the ﬁlesystemmetadata will be accessible. The ﬁle contents, even ﬁles protected with NSProtectionNone, are encrypted using keysderived from the Device Key and are not readable off of the original device unless the NSProtectionNone protection classkey (referred to as the “Class D Key”) has also been recovered from the device. This Class D Key is stored on the deviceﬂash storage but encrypted using the Device Key, which is in turn derived from the device-speciﬁc UID Key. The UID Keyis only usable through the encryption accelerator and is not directly accessible by the CPU. Even with this key, however,ﬁles protected with NSProtectionComplete will not be accessible without the User Passcode Key.File ProtectionAll ﬁles are encrypted with a unique File Key stored in an extended attribute of the ﬁle. Since this is stored within theﬁlesystem metadata, it is effectively protected by the File System Key. The File Key itself is protected by the Class Key,this Class Key is protected by the Device Key for NSProtectionNone and is protected by both the Device Key and theUser Passcode Key for NSProtectionComplete. The FIle Key is stored in the com.apple.system.cprotect extendedattribute with the format described in the table below.com.apple.system.cprotect Extended Attribute FormatTypeNameDescriptionuint32_txattr_versionVersion 2uint32_tunknownAppears unuseduint32_tpersistent_classProtection Class A-E (1-5)uint32_tkey_and_integrity_lengthAlways 40 bytesuint8_tpersistent_key[32]256-bit AES keyuint8_tpersistent_integrity[8]160-bit SHA1 hashiOS PasscodesThe Springboard application is responsible for presenting the lock screen and accepting the user’s passcode. Thepasscode is veriﬁed by passing it through the MobileKeyBag framework and to the AppleKeyStoreUserClientKeyBagUnlock method. In the kernel, the AppleKeyStore kernel extension derives the User Passcode Key through thePBKDF2 key stretching algorithm using AES with the UID Key as the pseudorandom function. This User Passcode Key isthen used to unwrap the Class Keys from the System KeyBag. If the unwrapping fails, then the KeyBagUnlock methodreturns that the passcode is incorrect.After successive incorrect passcode guesses, Springboard enforces a increasing “back-off” delay in order to deter casualpasscode guessing. In addition, the device may be conﬁgured to wipe itself after a chosen number of incorrect passcodeTrail of BitsApple iOS Security Evaluation2615

http://www.zdziarski.com/blog/?p=516guesses. These protections, however, are only enforced by the Springboard application, not the iOS kernel. With acustom command-line application on a jailbroken device, the passcodes can be guessed directly against theAppleKeyStoreUserClient without encountering an increasing delay or a forced device wipe.In the course of this assessment, such a tool was written and tested on a jailbroken iPhone 4. On this conﬁguration,passcodes could be guessed at an average rate of 9.18 guesses per second. This yields a maximum of 18 minutes toguess a simple 4-digit passcode.Data Protection API CoverageAn enumeration of all of the ﬁles metadata on a raw ﬁlesystem image identiﬁed only three ﬁles protected withNSProtectionComplete:•Data:/mobile/Library/Caches/Snapshots/com.apple.Preferences/UIApplicationAutomaticSnapshotDefault-Portrait@2x.jpg•Data:/mobile/Library/Caches/Snapshots/com.apple.VoiceMemos/UIApplicationAutomaticSnapshotDefault-Portrait@2x.jpg•Data:/mobile/Library/Mail/Protected IndexThese ﬁles indicated the only two aspects of iOS that make use of Data Protection: automatic screenshots andMobileMail. The automatic screenshots are taken when the user is in an application and hits the home button to return tothe Springboard screen. This causes a screen shrinking transition to be displayed using a screenshot of the currentapplication view. These screenshots are written to the ﬁlesystem protected using the Data Protection API. In addition,MobileMail uses Data Protection for stored e-mail messages and attachments. No other ﬁles or aspects of iOS werefound to use Data Protection for ﬁles stored on the ﬁlesystem.As was demonstrated by a research report from the Fraunhofer Institute for Secure Information Technology16, manypasswords in the Keychain are protected using kSecAttrAccessibleAlways and are accessible from a lost phone withoutrequiring knowledge of the user’s passcode. Their results are summarized for common built-in password types in thetable below.Password Keychain Item Protection ClassesPassword TypeKeychain Item Protection ClassMobileMail AOL Email AccountkSecAttrAccessibleWhenUnlockedCalDavkSecAttrAccessibleAlwaysMobileMail IMAP AccountkSecAttrAccessibleWhenUnlockedMobileMail SMTP AccountkSecAttrAccessibleWhenUnlockedMobileMail Exchange AccountkSecAttrAccessibleAlwaysiOS Backup PasswordkSecAttrAccessibleWhenUnlockedLDAPkSecAttrAccessibleAlwaysVoicemailkSecAttrAccessibleAlwaysVPN IPsec Shared SecretkSecAttrAccessibleAlwaysTrail of BitsApple iOS Security Evaluation2716“Lost iPhone? Lost Passwords! Practical Consideration of iOS Device Encryption Security”,http://sit.sit.fraunhofer.de/studies/en/sc-iphone-passwords.pdfPassword TypeKeychain Item Protection ClassVPN XAuth PasswordkSecAttrAccessibleAlwaysVPN PPP PasswordkSecAttrAccessibleAlwaysSafari Forms Auto-FillkSecAttrAccessibleWhenUnlockedWiFi WPA Enterprise with LEAPkSecAttrAccessibleAlwaysWiFi WPAkSecAttrAccessibleAlwaysTrail of BitsApple iOS Security Evaluation28AssessmentThe Data Protection API in iOS is a well designed foundation that enables iOS applications to easily declare which ﬁlesand Keychain items contain sensitive information and should be protected when not immediately needed. There are noobvious ﬂaws in its design or use of cryptography. It is, however, too sparingly used by the built-in applications in iOS 4,let alone by third-party applications. This leaves the vast majority of data stored on a lost device subject to recovery if aremote wipe command is not sent in time.The default iOS simple four-digit passcodes can be guessed in under 20 minutes using freely available tools, which willallow the attacker will physical access to the device to also decrypt any ﬁles or items in the Keychain that are protectedusing the Data Protection API. For this reason, it is crucial that sufﬁciently complex passcodes be used on all iOSdevices.Even with sufﬁciently complex passcodes, there are a number of sensitive passwords that may be recovered from a lostdevice, including passwords for Microsoft Exchange accounts, VPN shared secrets, and WiFi WPA passwords. Thisshould be taken into account and these passwords should be changed if an iOS device storing them is lost.Trail of BitsApple iOS Security Evaluation29