Quantcast
Channel: Elcomsoft iOS Forensic Toolkit – ElcomSoft blog
Viewing all articles
Browse latest Browse all 108

Extracting and Decrypting iOS Keychain: Physical, Logical and Cloud Options Explored

$
0
0

The keychain is one of the hallmarks of the Apple ecosystem. Containing a plethora of sensitive information, the keychain is one of the best guarded parts of the walled garden. At the same time, the keychain is relatively underexplored by the forensic community. The common knowledge has it that the keychain contains the users’ logins and passwords, and possibly some payment card information. The common knowledge is missing the point: the keychain contains literally thousands of records belonging to various apps and the system that are required to access lots of other sensitive information. Let’s talk about the keychain, its content and its protection, and the methods used to extract, decrypt and analyze the various bits and pieces.

The two sides of the keychain

The visible side of the keychain is passwords. iOS prompts users to save passwords users type in Safari. Password auto-fill service is available for both the Safari browser and apps. Users can access their stored passwords by opening the Settings app and navigating to [Passwords & Accounts] | [Website & App Passwords].

However, there is a lot more to the keychain than stored passwords. Applications use the keychain to store identities and authentication tokens, encryption keys and certificates. This is how Apple depicts keychain services in the developer documentation.

Source: Keychain Services

What is not visible to the user (but accessible to iOS developers) are Certificate, Key, and Trust Services. Certificates and identities are used to securely identify users in tamper-evident way. Cryptographic keys are used to encrypt, sign, and verify information. We’ll have a detailed discussion of the hidden treasures of the keychain in the next chapter.

The Apple ecosystem offers an easy way to synchronize keychain records across devices. This service has a name of iCloud Keychain.

In addition to the device keychain, there is also entity with similar name that lives in the cloud. iCloud Keychain is a service that synchronizes keychain records featuring the kSecAttrSynchronizable attribute via iCloud. If iCloud Keychain is activated, users restoring their devices will automatically receive all of their Safari passwords on their new device. Note that many things other than passwords (such as encryption keys, certificates and payment cards) will not synchronize to iCloud as they are not marked as kSecAttrSynchronizable. However, such keychain records still part of local and iCloud backups; they are wrapped with device UID, and can be only restored from a local or iCloud backup onto the same physical device (same UID) they were saved from.

The treasure trove

Most users know the keychain as a password manager keeping their authentication credentials, payment card data and similar bits and pieces of information. However, system-wise, the keychain stores a lot more than meets the eye.

According to Apple developer documentation, the keychain is “…a mechanism to store small bits of user data in an encrypted database called a keychain. […] The keychain is not limited to passwords. You can store other secrets that the user explicitly cares about, such as credit card information or even short notes. You can also store items that the user needs but may not be aware of. For example, the cryptographic keys and certificates that you manage with Certificate, Key, and Trust Services enable the user to engage in secure communications and to establish trust with other users and devices. You use the keychain to store these items as well.”

Only parts of that data are accessible to the user right from the device ([Settings] | [Passwords & Accounts] | [Websites & App Passwords]). Websites & App Passwords mostly contain authentication credentials (logins and passwords) users save in Safari and some of the apps via Shared Web Credentials.

Pretty much everything else cannot be viewed or otherwise accessed via the GUI. The additional pieces of information stored in the keychain by the system and apps may include:

  • Authentication tokens. These tokens are used to automatically authenticate users to online services without prompting for login and password. By extracting authentication tokens, experts may be able to access some of the users’ accounts without the need to login with a password while skipping two-factor authentication checks, where applicable. As an example, you may be able to use extracted tokens to sign in to Facebook, Google Account and other online services.
  • Shared secrets. A good example of such data are cryptographic seeds used by TOTP-compatible authenticator apps (e.g. Microsoft Authenticator or Google Authenticator).
  • Certificates and identities.
  • Encryption keys. These are used to encrypt and decrypt sensitive information, e.g. the password databases used by third-party password managers.

Keychain protection classes

In Keychain data protection overview Apple defines the available protection classes for the different types of keychain items via the kSecAttrAccessible attribute. This attribute controls the availability of the keychain item relative to the lock state of the device. Note: a device without a passcode is considered to always be unlocked, so keychain items stored with the first three attributes will be always available regardless of the device state.

Most importantly, some keychain items are, and some aren’t available in backups and iCloud Keychain. There are several things that affect availability, namely:

  1. ThisDeviceOnly If specified for a keychain item, that item is protected with the device UID, and cannot be restored onto a different physical device. ThisDeviceOnly items do not sync to iCloud.
  2. The passcode. Items protected with WhenPasscodeSetThisDeviceOnly will self-destruct if the passcode is removed. Since they also don’t sync to iCloud Keychain and are not extractable even from encrypted backups, removing the passcode from the device effectively renders WhenPasscodeSetThisDeviceOnly items inaccessible.
  3. iCloud Keychain. If this setting is enabled, keychain items marked as kSecAttrSynchronizable will sync to iCloud. Regardless of this settings, keychain items are included in iCloud backups (although in this case they are wrapped with device key, and can be only restored onto exactly the same device).
  4. iTunes backup password. If the password is set before a backup is produced, keychain items without ThisDeviceOnly will be encrypted with the backup password, and can be extracted and decrypted with Elcomsoft Phone Breaker. ThisDeviceOnly items are also included but additionally encrypted with device UID, which renders them non-transferrable and non-decryptable on anything but the original device. Unencrypted backups make all items encrypted with device UID, which makes the entire keychain non-transferrable and non-decryptable anywhere except the original device.

The following accessibility attributes are available:

Always Available (Before First Unlock)

kSecAttrAccessibleAlways makes keychain items always available, even if the device is locked or in the Before First Unlock (BFU) state. Only items marked with this protection class are extractable during the BFU extraction process (more on that later). Apple does not recommend this protection class for application use. Items with this attribute migrate to a new device when using encrypted backups.

After First Unlock

The After First Unlock condition occurs once the user unlocks the device for the first time after a restart. This condition is also satisfied if the device does not have a passcode. The AFU state remains true until the device is restarted. The kSecAttrAccessibleAfterFirstUnlock attribute is used by apps that utilize background refresh. The good practice is applying this class in to access only those keychain items that need to be accessed during background updates.

When Unlocked

The kSecAttrAccessibleWhenUnlocked attribute makes keychain items accessible only when the device is unlocked or does not have a passcode. This is the default accessibility setting when a protection class is not explicitly specified.

When Passcode Is Set – This Device Only

This is the highest available protection class. Items stored with the kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly class behave similar to items with the kSecAttrAccessibleWhenUnlocked attribute. However, they are only available when the device is configured with a passcode. According to Apple, such items:

  • Don’t sync to iCloud Keychain
  • Aren’t backed up

If the passcode is removed or reset, the items are rendered useless by discarding the class keys. (Source)

This Device Only

Keychain items stored without the ThisDeviceOnly suffix will sync to iCloud Keychain and will be transferred to another device via encrypted backups. Keychain items marked with ThisDeviceOnly are always protected with the device UID in all types of backups, which renders them useless if restored to a different device.

The ThisDeviceOnly attribute directly affects the availability of keychain items in various backups. If an item is marked with ThisDeviceOnly, it:

  • Will not sync to iCloud Keychain
  • Will be included in iCloud backups; however,
    • Can be only restored to the same physical device
  • Will be included in local backups (both encrypted and unencrypted); however,
    • Can be only restored to the same physical device

It is interesting to observe how some protection classes are connected with ThisDeviceOnly. Below is the full list of available combinations:

Always:

kSecAttrAccessibleAlways and kSecAttrAccessibleAlwaysThisDeviceOnly

After First Unlock:

kSecAttrAccessibleAfterFirstUnlock and kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly

When Unlocked

kSecAttrAccessibleWhenUnlocked and kSecAttrAccessibleWhenUnlockedThisDeviceOnly

When Passcode Is Set

Just kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly

The highest protection class (WhenPasscodeSet) is exclusively available in combination with ThisDeviceOnly. Such items are never transferred to another device, and are rendered useless if the passcode is removed from the device.

The lowest (non-) protection class specifying “always accessible” are currently listed as deprecated (since iOS 9). Deprecated protection classes can still be used for backward compatibility. The deprecation is one of the reasons the BFU extraction returns as few keychain records as it does.

BFU extraction: which keychain items are available?

As you have learned from the previous chapter, most keychain items are marked with attributes making them only accessible after the first unlock (AFU). Items marked with AFU access are encrypted with an encryption key derived from the device-specific information as well as the user’s screen lock password. Without the screen lock password, most keychain records will remain securely encrypted.

The only exception to this rule are records protected with the kSecAttrAccessibleAlways attribute irrespective of ThisDeviceOnly. This attribute ensures that affected keychain items always accessible, even before first unlock (the “BFU” state). While Apple had deprecated this security attribute, it is still used by a handful of developers (including Apple themselves) to store information that is considered essential for the system to boot. Examples of such records include some security keys. Keychain items with kSecAttrAccessibleAlways are also encrypted; however, the encryption is based solely on hardware credentials, and does not need the user’s screen lock password to decrypt. The BFU extraction process is therefore limited to kSecAttrAccessibleAlways items.

What is BFU extraction? This is the process of extracting available information from an iOS device that has not been unlocked even once after the device has been rebooted or powered on. Consider BFU a ‘cold’ extraction method, where everything encrypted with user credentials (the passcode) is not accessible. The most one can expect of BFU extraction are parts of the file system (unencrypted or encrypted with hardware credentials) and kSecAttrAccessibleAlways keychain items. The most common BFU extraction method involves jailbreaking with checkra1n that uses the bootloader vulnerability in a handful of iOS devices (generally, before the iPhone Xs, Xs Max and Xr range) or the direct exploitation of the checkm8 exploit.

Elcomsoft iOS Forensic Toolkit can be used to extract the available parts of the keychain in BFU mode. To perform BFU extraction, do the following.

  1. Make sure the device is compatible with the checkra1n
  2. Install checkra1n and connect the device to the PC.
  3. Launch Elcomsoft iOS Forensic Toolkit.
  4. Use the “K” command to perform keychain extraction.
  5. The accessible keychain items will be extracted and decrypted.
  6. Note that only records with kSecAttrAccessibleAlways attribute will be extracted irrespective of ThisDeviceOnly.

You may compare the number of keychain items extracted in BFU mode with regular AFU extraction. As you can see on the following screen shot, AFU extraction returns a significantly larger number of keychain items compared to BFU extraction.

The keychain is saved as a keychain_UDID_timestamp.xml (where the UDID is the unique ID of the device, and the timestamp is the date and time of the extraction).

You can analyze the extracted keychain items with the Keychain Explorer function of Elcomsoft Phone Breaker.

Among other data (which is mostly useless), we’ve unexpectedly discovered two passwords to Mail.ru and Rambler.ru mail accounts:

These are probably leaked from an insecure mail app (definitely not the iOS default Mail app) whose developers failed to choose the correct protection class for these passwords.

Read more about BFU extraction in BFU Extraction: Forensic Analysis of Locked and Disabled iPhones

iOS keychain 1: on the device

iOS devices keep the keychain in a single database file with the following name:

/private/var/Keychains/keychain-2.db

The file is a standard SQLite database, which by itself is not encrypted. However, individual records in the database are encrypted. In addition to the content of the record, some fields (such as acct, data, svce) are encrypted as shown in the below example of a keychain record:

The encryption is different depending on the type of the device.

32-bit devices (iPhone 5 and 5c and older, corresponding iPad and iPod Touch models)

Apple devices based on the 32-bit SoC are now history. Before Secure Enclave extracting the keychain was complex but doable. When processing a 32-bit iPhone (e.g. an iPhone 5c), one would need to download the keychain database and the encryption keys off the device. The decryption could be performed on the desktop. Each keychain element contained the following information in the data field:

  • Element version (2 or 3)
  • Protection class of the protection key that was used to encrypt the element key
  • The length of the encrypted element key (40 bytes)
  • Encrypted element key
  • Data encrypted with element key (AES-256-GSM)

The extraction tool (Elcomsoft iOS Forensic Toolkit) would first extract the Class Key for each protection class from the System Keybag, then use that key to decrypt the Element Key. The Element Key would be used to decrypt the data. (The keys from the System Keybag were also encrypted with a passcode-based key and/or a UID-based hardware key).

64-bit devices (iPhone 5s newer)

With the move to 64-bit SoC, Apple introduced Secure Enclave, a hardware-based key manager that is isolated from the main processor to provide an extra layer of security. Secure Enclave effectively blocks access to the System Keybag, making it impossible to decrypt keychain records outside the device.

We have developed a workaround to decrypt keychain records on the device. The keychaindumper utility (part of Elcomsoft iOS Forensic Toolkit) requests the iOS device to decrypt keychain elements and reads the result. To decrypt all keychain records, keychaindumper enumerates the keychain by calling SecItemCopyMatching. This method has two restrictions.

First, it only works on the device, and requires the display to remain unlocked (otherwise higher protection class items would not be available).

The second restriction is a bit more difficult to explain. Not only does the tool need a jailbreak (or a sandbox escape/privilege escalation exploit as used in the extraction agent), but it must be signed with a special set of entitlements. These entitlements specify the wildcard [*] for the keychain-access-group key so that the tool has access to all elements.

This restriction has two consequences. First, not every exploit has the ability to disable signature verification. Second, iOS 13.5 gets rid of the wildcard, so one must first enumerate all access groups declared in the keychain and use those groups to sign the keychaindumper utility.

For the end user, however, keychain extraction looks easy. Depending on whether you are processing a jailbroken device or are relying upon the built-in extraction agent, you would use either the “D” and then “K” commands or the “1”, “2” and “4” sequence to install the acquisition agent, extract the keychain and remove the agent from the device.

You will be prompted to enter the passcode on the device screen. After that, keychain extraction finishes in a matter of seconds.

To view the iCloud Keychain, use Elcomsoft Phone Breaker.

  1. Launch Elcomsoft Phone Breaker.
  2. Click Keychain Explorer.
  3. In Keychain Explorer, select the corresponding xml file you have specified during the extraction.
  4. The keychain records will be listed.

iOS keychain 2: local backups

Local backups are an excellent way to obtain parts of the keychain. Interestingly, the keychain is available in iTunes backups created with or without a password; however, the encryption methods are very different between the two types of backups.

Password-protected (encrypted) backups

If the user (or expert) specifies a password before creating an iTunes-style backup, the entire content of the backup including the keychain will be encrypted with the encryption key derived from that password.

Keychain items (except for ThisDeviceOnly records) can be decrypted using the same password as specified at the time of creating the backup. Notably, such records include all the passwords the user saved in the Safari browser, but not, for the most part, the encryption keys, certificates, or payment cards. Relatively few system-wide records are stored as ThisDeviceOnly, mostly including some Apple certificates and Apple service keys stored in the beginning of the keychain. Obviously, third-party app developers are free to choose ThisDeviceOnly should they require using the highest protection class for their data.

Items protected with ThisDeviceOnly are encrypted with a hardware-specific key (UID encrypted), and cannot be decrypted from the backup whether or not the password is known. These records can be only restored onto the same device (same UID) they have been saved from.

Unencrypted backups (without a password)

If a local backup is created without a password, all keychain items that are included in the backup are encrypted with a device-specific hardware key (UID), which effectively makes it possible to restore those items onto exactly the same device the backup was made from. Restoring a backup without a password onto a different device will not transfer any of the keychain records. This is similar to the way Apple handles keychain records in iCloud backups.

As a result, you can only access keychain records stored in password-protected backups, and only if you know the password. We provide the Keychain Explorer tool built into Elcomsoft Phone Breaker that can help you analyze the keychain from iTunes backups.

To view the keychain, do the following.

  1. Launch Elcomsoft Phone Breaker.
  2. Click Keychain Explorer.
  3. In Keychain Explorer, open the backup and enter the password.
  4. It will take some time (up to several minutes, depending on the size of the backup) to extract and decrypt the keychain.
  5. The keychain records will be listed as seen in the window below.

iOS keychain 3: iCloud backups

In many ways, iCloud backups are similar in content to iTunes backups created without a password. iCloud backups may or may not include a copy of the user’s keychain depending on whether or not the user had enabled iCloud Keychain.

According to Apple, “iCloud Keychain items aren’t part of iCloud Backup because they already live in the cloud. To find your iCloud Keychain items […], tap Settings > [your name] > iCloud > Keychain and turn on iCloud Keychain.”

In a discussion on the Apple developer forum, the following statement is made:

“I had a re-read of the iOS Security document, which has a specific section on iCloud Backup. That makes it clear that iCloud Backup acts like an iTunes backup without a password: the keychain items are included in the backup but they are wrapped with a device-specific key. Thus, they can only be restored to the device that originally backed them up, which means that they get lost when you restore the backup to a different device (which is how you tested this).”

Similar to iTunes backups without a password, keychain items are encrypted with a device-specific, hardware key. In a way, all of the keychain items receive the protection offered by “this device only” protection class because they can be only restored onto the same physical device the iCloud backup was created from. If the iCloud backup is restored onto a different device (even of the same model), the keychain items will not be restored. Users who want to transfer their stored passwords onto a different device must use a password-protected local backup or enable iCloud Keychain and wait for the keychain to finish synchronizing.

You cannot view or analyze the copy of the keychain stored in iCloud backups.

iOS keychain 4: iCloud Keychain

Introduced in iOS 7.0.3, iCloud Keychain is essentially Apple’s take on password managers. iCloud Keychain synchronizes users’ passwords across all of the user’s devices belonging to the Apple’s ecosystem. Apple defines iCloud Keychain as follows. “With iCloud Keychain, you can keep your passwords and other secure information updated across your devices. iCloud Keychain remembers things, so that you don’t have to. It auto-fills your information—like your Safari usernames and passwords, credit cards, Wi-Fi passwords, and social log-ins—on any device that you approve.”

Considering the highly sensitive nature of iCloud Keychain, Apple takes unprecedented measures to protect its content. This is what Apple has to say about iCloud Keychain protection: “iCloud protects your information with end-to-end encryption, which provides the highest level of data security. Your data is protected with a key that’s made from information unique to your device, and combined with your device passcode, which only you know. No one else can access or read this data, either in transit or storage.”

The protection features include:

  1. You can only use iCloud Keychain if your Apple Account has Two-Factor Authentication enabled. This rule is enforced in all regions since the release of iOS 13.
  2. There are exceptions from the first rule, e.g. if a pre-iOS 13 device is used in one of the regions where Apple still did not complete rolling out Two-Factor Authentication. In these cases, the iCloud Keychain must be protected with a dedicated Security Code (six digits, complex alphanumerics, or randomly generated to authorize additional devices and verify the user’s identity).
  3. The user’s iCloud Keychain is encrypted with a key derived from the enrolled device passcode. In order to enroll an additional device, the user must provide the screen lock passcode (or system password) to one of the already enrolled devices.
  4. When it comes to iCloud Keychain, Apple limits the number of attempts to “guess” the passcode. If an incorrect passcode is entered several times in a raw, the iCloud Keychain is removed from Apple’s servers and must be set up again. Apple does not specify the exact number of incorrect attempts that will trigger the keychain removal. We tested it to be 10 attempts; however, this number may change at any time.
  5. Only items marked as kSecAttrSynchronizable are synchronized to the cloud.

That last sentence needs clarification. The In the Depths of iCloud Keychain article by hackmagnet has the following statement:

“It should be noted that not the entire Keychain is synced. Some records are tied to a device (e.g., VPN accounts), and should not leave the device. Only the records with the attribute ‘kSecAttrSynchronizable’ are synced. Apple has set this attribute for Safari user data (including user names, passwords and credit card numbers) and for Wi-Fi passwords. In addition, the records of third-party applications are not synced by default. To allow their syncing, the developers must explicitly set the attribute ‘kSecAttrSynchronizable’ when adding the record to Keychain.”

Compared to other data users store in iCloud, the keychain occupies limited space and stored on Apple servers in Cupertino. Does that mean that Apple can access your passwords? No. iCloud Keychain is encrypted with a key which, in turn, is “wrapped” with the user’s screen lock passcode (iOS) or system password (macOS). In order to unwrap the encryption key, the correct passcode must be provided. While it’s incredibly easy for Apple to build a piece of software allowing the company to brute-force the passcodes, unwrap the encryption key and decrypt the keychain, the company publicly refuses to do so. At this time, Apple does not “know” your passwords even if it stores them on their servers. This, by the way, is very different from Google, which does, in fact, “know” your passwords. If you are interested in obtaining Chrome passwords from the user’s Google Account, try Elcomsoft Cloud Explorer.

How to Extract iCloud Keychain with Elcomsoft Phone Breaker

iCloud Keychain records are protected with what Apple calls “end-to-end encryption”. Several layers of encryption are involved, the last one being the “wrapped” keys that are required to decrypt keychain records. In order to “unwrap” the keys, one must provide the user’s screen lock passcode or system password (Mac) of one of the already enrolled device. That requirement is in addition to the usual authentication requirements (login and password, one-time code to pass two-factor authentication).

In order to extract iCloud Keychain, do the following.

  1. Launch Elcomsoft Phone Breaker.
  2. Sign in to the user’s Apple Account using the full authentication procedure (Apple ID, password, and two-factor authentication).
  3. You will be presented with the list of enrolled devices. During the next step, select the device you know the screen lock passcode (or system password) to, and type in the passcode or password in the corresponding field.
  4. In the list of data categories, select iCloud Keychain.
  5. Click Next to download.
  6. The iCloud Keychain will be downloaded and decrypted.

Viewing iCloud Keychain

We have two tools that can help you analyze the keychain you’ve downloaded from iCloud. While the two tools serve different purposes, you’ll have very similar experience when accessing keychain data with either one.

The first tool is Elcomsoft Phone Breaker. Historically, this was the first tool we’ve implemented the keychain analysis. To view the iCloud Keychain, do the following.

  1. Launch Elcomsoft Phone Breaker.
  2. Click Keychain Explorer.
  3. In Keychain Explorer, select the iCloud Keychain you’ve just downloaded.
  4. The keychain records will be listed momentarily as seen in the window below.

Note: Elcomsoft Phone Breaker will automatically offer to explore the iCloud Keychain during the last step.

In addition to Elcomsoft Phone Breaker, we have a dedicated tool designed for viewing data and performing lightweight forensic analysis. We have added the ability to analyze keychain records to Elcomsoft Phone Viewer relatively recently. Today, it has the same viewing/analysis features as Elcomsoft Phone Breaker when it comes to exploring the iCloud Keychain.

To explore the iCloud Keychain in Elcomsoft Phone Viewer, do the following.

  1. Launch Elcomsoft Phone Viewer.
  2. Click Keychain Explorer.
  3. In Keychain Explorer, open the downloaded keychain file.
  4. The keychain records will be listed.

The bonus chapter: macOS keychain

macOS is an equal part of the Apple ecosystem. Just like the mobile devices, Mac computers have the keychain. Stephanie Thompson, Blackbag Solutions Engineer, wrote an excellent article about the macOS keychain: Apple Keychain Parsing in BlackLight

We have a tool for that, too. Elcomsoft Password Digger offers the ability to extract, decrypt and export the content of the macOS system and user keychains. You can use the tool to build a custom dictionary containing all of the user’s stored passwords, and use that dictionary in a password recovery tool of your choice to improve password recovery attacks. In addition, you can export the full content of the keychain into an unencrypted XML file.


Viewing all articles
Browse latest Browse all 108

Trending Articles