Skip to content

Instantly share code, notes, and snippets.

@cyphunk
Last active May 28, 2018 00:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyphunk/dd95abf1623f9cb0a9d485471675fda5 to your computer and use it in GitHub Desktop.
Save cyphunk/dd95abf1623f9cb0a9d485471675fda5 to your computer and use it in GitHub Desktop.
notes from iOS security documentation that I used to write https://deadhacker.com/2016/03/25/the-terrorists-phone/

Notation iOS 9

This homebrewed notation I typically use when evaluating secure boot designs of embedded devices. It doesn't apply accurately for the iOS review, hides the key-wrapping schema for example. But it's enough to keep track of storage location of secrets and some interdependency.

pfk                  = 256bit per_file_key
iv                   = sha1() "block offset into file"
nand://enc_file      = aes(file, key=[pfk, iv])
classk               = ?
wrapped_pfk          = wrap_rfc3394(pfk, key?=classk)
effstorage://fsk     = rnd() file_system_key on first install or wipe
nand://enc_file_meta = enc([wrapped_pfk, "classnote"], key=fsk)

Some parts of the documentation were not clear to me. Could be due to a lack of understanding some of the crypto-schemes utilized or just an issue of more verbose description missing.

  A6                A7              A8              A9              A10
  09/2012-09/2015   09/2012-now     09/2014-now     09/2015-now     09/2016?
                    Secure Enclave  
  iPhone 5, 5c      iPhone 5S,      iPhone6, 6+     iPhone 6S, 6S+  iPhone 7?
                    iPad mini 3
  NAND:             NAND:           NAND:
  THGBX2G7B2JLA01   H2JTFG8YD2MBR   SDMFLBCB2
                                    H2JTDG8UD1BMS
                                    
                                    

iOS 9 Security Document Excerpts

https://www.apple.com/business/docs/iOS_Security_Guide.pdf

Page 7.

Additionally, data that is saved to the file system by the Secure enclave is encrypted with a key entangled with the UID and an anti-replay counter.

Page 10.

The UID allows data to be cryptographically tired to a paticular device. For example, the key hierarchy protection the file system includes the UID, so if the memory chips are physically moved from one device to another the files are inaccessible.

Securely erasing saved keys is just as important as generating them. It’s especially challenging to do so on flash storage, where wear-leveling might mean multiple copies of data need to be erased. To address this issue, iOS devices include a feature dedicated to secure data erasure called Effaceable Storage. This feature accesses the underlying storage technology (for example, NAND) to directly address and erase a small number of blocks at a very low level.

Page 11.

The initialization vector (IV) is calculated with the block offset into the file, encrypted with the SHA-1 hash of the per-file key.

The per-file key is wrapped with one of several class keys, depending on circumstances under which the file should be accessible. [RFC 3394] The wrapped per-file key is stored in the file's metadata.

The metadata of all files [metadata includes wrapped per-file key] is encrypted with a random key, which is created with iOS is first installed or when the device is wiped by a user. The file system key is stored in Effaceable Storage. [my understanding is Effacable Storage is on NAND. Also I suspect 'file system key' is the random key described in the sentence before]. Since it's stored on the device, the key is not used to maintain the confidentiality of data; instead, it's designed to be quickly erased on demand. ... Erasing the key in this manner renders all files cryptographically inaccessible.

Page 12.

The content of a file is encrypted with a per-file key, which is wrapped with a class key and stored in a file’s metadata, which is in turn encrypted with the file system key. The class key is protected with the hardware UID and, for some classes, the user’s passcode.

Basically passcode is relevant in file encrypt/decrypt depending on class.

The passcode is entangled with the device's UID, so brute-force attempts must be performed on the device under attack. A large iteration count is used to make each attempt slower. The iteratoin count is calibrated so that one attempt takes approximately 80 milliseconds.

To further discourage brute-force passcode attacks, there are escalating time delays after the entry of an invalid passcode at the Lock screen. If Settings > Touch ID & Passcode > Erase Data is turned on, the device will automatically wipe after 10 consecutive incorrect attempts to enter the passcode.

On devices with an A7 or later A-series processor, the delays are enforced by the Secure Enclave.

secure enclave is the coprocessor (or TrustZoney apple thingy). "Enforcement" could mean scheme that dictates number of iterations based on 80ms average computation. Or it could mean enforcement of counter and increased software delay. But the question is does this indicate that the counter and software enforced delay are "stored" in memory within the Secure Enclave processor?

Complete Protection (NSFileProtectionComplete): The class key is protected with a key derived from the user passcode and the device UID. Shortly after the user locks a device (10 seconds, if the Require Password setting is Immediately), the decrypted class key is discarded, rendering all data in this class inaccessible until the user enters the passcode again or unlocks the device using Touch ID.

page 15.

The keys for both file and keychain Data Protection classes are collected and managed in keybags.

System keybag is where the wrapped class keys used in normal operation of the device are stored. For example, when a passcode is entered, the NSFileProtectionComplete key is loaded from the system keybag and unwrapped. It is a binary plist stored in the No Protection class, but whose contents are encrypted with a key held in Effaceable Storage. In order to give forward security to keybags, this key is wiped and regenerated each time a user changes their passcode. The AppleKeyStore kernel extension manages the system keybag, and can be queried regarding a device’s lock state. It reports that the device is unlocked only if all the class keys in the system keybag are accessible, and have been unwrapped successfully

Other Discussions

http://www.freerepublic.com/focus/news/3420540/posts?page=48#47

First, the iPhone 5C doesn't use a Secure Enclave. It has an earlier iteration of the technology that is actually imbedded in the Apple A6 processor called the Encryption Engine which is a dedicated co-processor.

Also stored in that EEPROM is a one-way hash of the user's passcode. This is stored instead of a copy of the passcode and the algorithm used to create the one-way hash recreates it each time the user inputs his passcode and that one-way hash is compared to the one in memory as a test to see if it matches. If it does, then the data encryption key is regenerated by entangling all four pieces and the iPhone is unlocked. If not, the count is iterated, and another passcode attempt is permitted. Four attempts are allowed with no delay, then several more with escalating time factors. On the tenth attempt, it is NOT the data encryption key that gets erased , but the stored one-way hash of the user's passcode, forever preventing the reconstruction of the data encryption key.

However, It would be much more difficult for the iOS devices on A7 and later devices with the Secure Enclave which is much more highly protected from reading anything stored on them. . . and each of four different ICs have to be registered with each other and recognize if they have been removed by from the circuit and replaced or modified, requiring they be re-registered, a process that only Apple can do. "

I'm not certain but don't think the success of the attack depends on if a Secure Enclave is used or not. It may effect the method for resetting the passcode attempt counter but not preventing wipe.

What the author calls the stored one-way hash of user's passcode is what I call the random filesystem key? This or he may have looked at iOS documentation i missed. Thread:

http://www.freerepublic.com/focus/news/3420540/posts?q=1&;page=51#56

http://www.freerepublic.com/focus/news/3420540/posts?page=61#61

https://blog.trailofbits.com/2016/02/17/apple-can-comply-with-the-fbi-court-order/

A summary of the ios documentation.

Etc

https://media.blackhat.com/bh-ad-11/Belenko/bh-ad-11-Belenko-iOS_Data_Protection.pdf

With iOS 4 Effaceable Storage = 960 bytes and contains System Keyback+IV, NSProtectedNone class key and File system key. (slide 24)

Acquiring disk image is not enough for iOS 4+ – Content protection keys must also be extracted from the device during acquisition – Effaceable Storage contents are also needed to decrypt dd images. (slide 45)

Still not indicating Effaceable Storage is located in tamper resistant place.

http://esec-lab.sogeti.com/static/publications/11-hitbamsterdam-iphonedataprotection.pdf

Also a good overview with great detail for A4 devices iOS 4.3.

  • Slide 30 - storage overview
  • Slide 31 - explains IV = logical block number
  • Slide 32 - iOS 3 EMF (likely fsk in my notation) stored in data partition last block. iOS 4 EMF stored in Eff storage
  • Slide 34 - iOD 4 NAND layout - plog=Effaceable Storage
  • Slide 36 - AppleEffaceableNAND - 4 groups (1 block in each bank) of 96 unites (pages)
    [384 pages? which is quiet a lot more than we see the SecureCore/Trustzone comparison later]
  • Slide 40 - AppleEffaceableStorage IOKit API: getCapacity = 960 bytes
  • Slide 45 - Data Whipe: Erase DKey, Erase EMF key, generate new system bag

http://esec-lab.sogeti.com/posts/2011/10/09/ios-5-data-protection-updates.html

iOS 5 was released this week ... This post highlights the updates made since iOS 4.

File encryption IV uses block offset (BO) in file instead of block LBA. Actually: IV = aes128(BO, key-iv=sha1(filekey)[:16])

Post also provides a good short but detailed overview of file encryption step.s

https://www.trailofbits.com/resources/ios4_security_evaluation_paper.pdf

Now [iOS4], the entire filesystem can be rendered unreadable by simply wiping a single encryption key (referred to here as the File System Key)

Seems to indicate wipe still utilizes file system key rewrite in iOS 4 as well as recent iOS9.

The Springboard application is responsible for presenting the lock screen and accepting the user’s passcode.

After successive incorrect passcode guesses, Springboard enforces a increasing “back-off” delay in order to deter casual passcode guessing. In addition, the device may be configured to wipe itself after a chosen number of incorrect passcode guesses. These protections, however, are only enforced by the Springboard application, not the iOS kernel. With a custom command-line application on a jailbroken device, the passcodes can be guessed directly against the AppleKeyStoreUserClient without encountering an increasing delay or a forced device wipe.

http://sit.sit.fraunhofer.de/studies/en/sc-iphone-passwords-faq.pdf

As of this writing, all versions of iOS up to (and including) iOS 6.0.1 are affected by the described attack method.

Method:

https://www.sit.fraunhofer.de/fileadmin/dokumente/studien_und_technical_reports/Whitepaper_Lost_iPhone.pdf iPhone 4 with iOS 4.2.1 (or 6.0.1 as indicated in FAQ above). Uses SSH on unwiped device, somehow (jailbreak, ramdisk attack, they dont say) to crack some keychain entries on the device

http://www.a-sit.at/pdfs/Technologiebeobachtung/ios-encryption-systems.pdf

Unfortunately, not including the user’s passcode in the protection system is a major weak- ness that can be exploited by an attacker. Therefore, the file-system encryption system is primarily used to provide basic protection and to implement the quick- remote wipe functionality.

Seems a bit out of date (pre iOS4 or so)

The pro-tection of the EMF (file system key) and Dkey (device key) keys for encrypting the file-system is not based on the passcode of the user, but relies only on the integrated secure element . Thus, even when a passcode is set on the device, the application of a jailbreak enables the attacker to gain root access to the operating system, which decrypts the data with the EMF and Dkey keys.

http://www.apple.com/pr/library/2013/09/10Apple-Announces-iPhone-5s-The-Most-Forward-Thinking-Smartphone-in-the-World.html

A7 press release, iPhone 5s, iOS 7

All fingerprint information is encrypted and stored securely in the Secure Enclave inside the A7 chip on the iPhone 5s

iPhone 5s comes with iOS 7, the most significant iOS update since the original iPhone

https://www.quora.com/What-is-Apple%E2%80%99s-new-Secure-Enclave-and-why-is-it-important

Assuming Secure Enclave related to Trust Zone

Apple has customized a highly optimized version of TrustZone and created what is now known Secure Enclave. Of course Apple will likely never release the details of what they do in the custom hardware for number of reasons. Thus I will speak directly of TrustZone and extrapolate to Secure Enclave.

http://wiki.iphone-dataprotection.googlecode.com/hg/EffaceableArea.wiki

Trustzone / SecurCore

It's highly unlikely that the Secure Enclave is trustzone because iOS9 Security Documentatoin specifically describes it as a "coprocessor". But, assuming A7 Secure Enclave may bare some resemblences to ARM TrustZone we would hope to find some hints of internal FLASH in documentation. Could not find very detailed specs but based on what I did find the architecture does work on various processors that have enough internal memory for key and value storage and building a Secure Enclave with protected non NAND memory.

ST SecurCore SC300 http://www.st.com/st-web-ui/static/active/en/resource/technical/document/data_brief/DM00141524.pdf

  • 2048 Kbytes of User Flash memory

Atmel SecurCore SC100 http://pdf.datasheetcatalog.com/datasheet/atmel/1575s.pdf

  • 256K ROM Program Memory
  • 72K Bytes of EEPROM User Memory, Including 256 OTP Bytes

ST SecureCore SC000 http://www2.st.com/content/st_com/en/products/secure-mcus/st31-secure-sc000-mcus.html

  • 320K ROM
  • 52K EEPROM

More trust-zone doc but doesnt detail memory hardware software tie in, just high detail of software virtualization http://infocenter.arm.com/help/topic/com.arm.doc.prd29-genc-009492c/PRD29-GENC-009492C_trustzone_security_whitepaper.pdf https://genode.org/documentation/articles/trustzone

TrustZone NAND?

http://www.design-reuse.com/articles/16975/arm-security-solutions-and-intel-authenticated-flash-how-to-integrate-intel-authenticated-flash-with-arm-trustzone-for-maximum-system-protection.html

Press release from Intel+ARM

combination of ARM's Security Solutions, including TrustZone, with Intel Authenticated Memory

The Intel Authenticated Flash memory also provides authenticated memory access control and protected key storage features

As well as providing full on-chip security for a SoC device, TrustZone can also be extended to enable security on systems that utilize offchip memory. While this architecture is inherently less safe from physical attack than a system that uses on-chip memory (for example, it can be removed and interfered with) TrustZone can nevertheless enhance the overall security of such systems. Although the architectural aspects of TrustZone are implemented within the latest ARM11 CPUs, the TrustZone Software introduces the concept of open APIs to enable a rich ecosystem that can indeed be extended to all the ARM CPUs.

"TrustZone ... ecosystem that can indeed be extended to all the ARM CPUs"

A TrustZone-based SoC implementation will consist of both secure and non-secure elements. Key components include:

On-chip non-volatile or one-time programmable memory for storing device or master keys

And user keys?

Memory:

Intel Authenticated Flash consists of a standard flash memory that has integrated an RSA engine, a SHA- 1 engine and a hardware RMG (random number generator).

Even if the operating system were compromised, it would not be able to correctly generate a signed request to the Intel Authenticated Flash memory.

Even so... a MiTM to drop a legit signed request to change wipe key or passcode attempt counter could be prevented. The question is can a rolling session be created to force writes to happen or else fail in some dramatic way.

Intel Authenticated Flash memory operates by authenticating command requests to the flash memory. The flash memory will independently validate the signature presented with the command. If the signature is correct, the command proceeds. If the signature is incorrect, the operation is terminated and not allowed to proceed. (Figure 5)

At least one iPhone 6 is using Samsung 32GB KLMBG4GEAC (no authenticated write). Likely others do not provide or support authenticated write but could check some other time.

Not TrustZone

https://news.ycombinator.com/item?id=8410700

Digging Further

Jonathan Zdziarski suggested RE of the AppleKeyStore kernel extension. If time permits the route for obtaining iOS kexts https://www.theiphonewiki.com/wiki/Kernel#Kernel_Extensions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment