DemystifyingApple”Pie”&TouchID
Disclaimer• Apple Pay research is work in progress.
• Yes, a jailbroken device is required.
• No 0-day vulnerabilities in this talk.
• This talk is about Apple Pay internals and TouchID implementation.
Download the slides from:twitter.com/0xroot
Agenda•Part I: Introduction to Apple Pay.•Part II: Demystifying Apple Pay.•Part III: Messing with runtime.•Part IV: TouchID implementation caveats.
whoami
Sebas Guerrero (@0xroot)Sr. Mobile Security Analyst at NowSecure
https://github.com/[email protected]
IntroductiontoApplePay
WhatisApplePay?
“Mobile payments service and digital wallet app that uses NFC to initiate secure payment transactions between contactless payment terminals and Apple
iOS devices.”
HowcanIuseit?• Pay in-store Purchase by just tapping the
phone against a contactless POS and placing the finger on the TouchID
• Pay in mobile apps Pay for items within mobile apps that support ApplePay
SE&HCE• Secure Element (SE) - Tamper-resistant platform capable of securely hosting
applications and their confidential and cryptographic data in accordance with the rules and security requirements. It can be considered a chip that offers a dynamic environment to store data securely.
• Host Card Emulation (HCE) - Assumes that any data stored on a handset is vulnerable and therefore restricts the storage of sensitive data to host or ‘cloud’ databases, managed to a high security standard. Preventing unauthorized access depends on four pillars: limited use key, tokens, device fingerprinting and transaction risk analysis.
DemystifyingApplePay
WhatcomposesApplePay?
SEnclave & TouchID
ApplePay Servers
Passbook Secure Element
NFC Controller
WhatisstoredintheSE?“Every time a consumer adds a credit card to the Passbook
application, the real payment credentials like the PAN, Expiration Date, CVV, etc. are not stored into the SE.
Apple Pay instead stores a token and some associated data inside the SE.”
Whatisthetokenused?“We can consider a token like a fake credit card number. Which is de-tokenized before being transmitted on to the
Issuer for authorization.
The Acquirer is the responsible for tokenization and de-tokenization. But, Apple Pay uses the standard created by
EMVCo, being the payment network the one that performs de-tokenization.”
Howarethetokensprovided?
Customer Apple Pay Apple Pay Servers
Issuer Bank
Token Service Provider
Secure Element
Credit cardPAN / Exp. Date / CVV
PAN / Exp. Date / CVV Token / Token-key
PAN / Exp. Date / CVV
Token / Token-key /cvv-key
Token / Token-key /cvv-key
- token-key will be used to generate a dynamic cryptogram- cvv-key will be used to generate a dynamic security code
PaymenttokenformatPKPaymentToken Object
Transaction ID
Payment Network
Payment Token DataSignatureHeader
Encrypted Payment DataAmountCardholder name….
Payment Processing Data
Top-Level Structure
Key Value Description
data Payment data dictionary, Base64 encoded as string
Encrypted Payment Data
header Header dictionary Additional information used to decrypt and verify the payment.
signature Detached PKCS #7 signature, Base64 encoded as string
Signature of the payment and header data.
version String Version information about the payment token.
PaymenttokenformatPayment Data Keys
Key Value Description
applicationPrimaryAccountNumber
string Device-specific account number of the card that funds this transaction.
applicationExpirationDate date (string)
Card expiration date in the format YYMMDD.
currencyCode string ISO 4217 numeric currency code.
transactionAmount number Transaction amount.
Key Value Description
cardholderName string Cardholder name.
deviceManufacturerIdentifier
string Hex-encoded device manufacturer identifier.
paymentDataType string Either ‘3DSecure’ or ‘EMV’.
paymentData payment data dictionary
Detailed payment data
Interceptingpaymentoperations“According to EMV standard, during a payment operation, sensitive information like card-holder name, credit card number, expiration date and
cvv are transmitted.”
proxmark3> hf 14a listRecorded Activity Start | End | Src | Data —---------|-----------|-----|-------- 0 | 992 | Rdr | 52 298272 | 299264 | Rdr | 52 596560 | 597552 | Rdr | 52 894832 | 895824 | Rdr | 52
1193120 | 1194112 | Rdr | 52 1491392 | 1492384 | Rdr | 52 1789680 | 1790672 | Rdr | 52 2087952 | 2088944 | Rdr | 52 2386240 | 2387232 | Rdr | 52 2684496 | 2685488 | Rdr | 52 2982800 | 2983792 | Rdr | 52 3281088 | 3282080 | Rdr | 52 3579360 | 3580352 | Rdr | 52 …
Tokende-tokenization{ "data": “2DzU9u6byIY4qCs3lW4KgK3JWC6Ac+x…..……WkFco=“, "header": { "ephemeralPublicKey": “MFkwEwYHKoZIzj0…………bA==“, "publicKeyHash": "spzGX6upCJhx5UD8vCo1+LcIi7+fkxEUaVmhbX18cJM=", "transactionId": "79ccd07eb432f80067d8e5bbc4c38ee1def7fcc1827f6ba5b63bf47b283ebf89" }, "signature": “MIAGCSqGSIb3DQEHAqtNGjj9I………….AAAAAAAA=“, "version": "EC_v1"}
{ "applicationExpirationDate": "190131", "applicationPrimaryAccountNumber": "370295XXXXX5435", "currencyCode": "840", "deviceManufacturerIdentifier": "XXXXXXXXXX", "paymentData": { "emvData": “nycBgJ82AgDCnyYIG2vuQydGkMafEA…….Lnvab4=“ }, "paymentDataType": "EMV", "transactionAmount": 100}
Github: applepay_crypto_demo
Whathappensinapayment?“Each transaction is authorized with a one-time unique number using your
Device Account Number and instead of using the security code from the back of your card, Apple Pay creates a dynamic security code to securely validate
each transaction.”- From the press release
The Device Account Number represents the Token, the One-time Unique Number represents the dynamic cryptogram and the Dynamic Security Code
represents the dynamic CVV
SecureEnclave• Part of the A7 and A8 chips used for Touch ID. According to Apple, within the Secure
Enclave, the fingerprint data is stored in an encrypted form which can only be decrypted by a key available by the SecureEnclave thus making fingerprint data walled off from the rest of A7/A8 chip.
• It’s a flashable 4MB processor named the Secure Enclave Processor (SEP).
• It contains its own OS called SEP OS and there is an utility called SEPUtil that can be used to communicate with it.
• It’s contained in the ramdisk of H7SURamDisk.dmg which is located in /usr/standalone/update/ramdisk and there in /usr/libexec.
• Is necessary to strip off the first 0x1b (27) bytes to make the DMG readable.
RootǝdCON
SecureEnclave• We believe that all the information being stored
in the SecureEnclave is erased once the device is turned off.
• Inside biometrickitd we find at memory address ‘000000010001DD3C’ a ‘bl sub_10001376c’ instruction. Such method is the one used to upload all the information to the SecureEnclave.
• Probably a good starter point to figure out how things work in the SecureEnclave.
RootǝdCON
Messingwithruntime
TouchID“Fingerprint recognition feature, designed by Apple
and available on the iPhone 5S, 6 and 6+. Which has as purpose to allow users to unlock their
device, as well as make purchases in the various Apple stores and to authenticate Apple Pay online
or in apps.”
TouchIDProcessSense for
scannable object Scan objectConstruct input map based on scan results
Construct lower resolution
input pattern
Provide input pattern and
template pattern
Run match comparisons of
input pattern and template pattern
Provide identity of possible match
results
Run match comparison of input map with possible match
identities
Provide result
Whathappensunderthehood• First Obstacle What is happening at filesystem level when the user interacts with
the TouchID component and a new fingerprint is added/removed into/from the system?
• Workaround FileMon utility, made by J. Levin, into steroids thanks to Pancake. Lets the user to peek behind the scenes what iOS Daemons are doing.
• Goal We obtain the binaries involved and their operations performed when the Apple Pay technology or TouchID component are used.
Identifyingbinaries
• SpringBoard framework binary generates sort of interesting images.• biometrickitd daemon creates and modifies the content of a file called TemplateList.cat
[E] Error copying /tmp/_private_var_root_Library_Catacomb_TemplateList.cat.tmp
Overridingunlinkcarapene:~ root# cycript -p PIDcy# @import com.saurik.substrate.MScy# unlink = dlsym(RTLD_DEFAULT, “unlink")cy# unlink = @encode(void *(char *, char *))(unlink)cy# var oldu = {}cy# var log = []
cy# MS.hookFunction(unlink, function(path){cy> log.push([path]);cy> return 0;cy> }, oldu)
• Second Obstacle Unlink method avoid us from copying the resource, since it removes the link named by the path parameter from its directory right after before we can copy it.
• Workaround Override its implementation and return always false.
• Goal Obtain a copy of the files generated.
dyld_shared_cache• Third Obstacle Since iPhoneOS 3.1 all default (private and public) libraries have been
compiled into a big cache file. All binaries or libraries from /System/Library/Frameworks and /System/Library/PrivateFrameworks are now located in /System/Library/Caches/com.apple.dyld/dyld_shared_cache_armX
• Workaround Makes use of jtool utility, extracting a specific binary from the cache, or dumping all the binaries at once.
• Goal Access to all the binaries, and the ability to dump their classes/methods and RE their source code.
jtool -extract UIKit path/to/dyld_shared_cachejtool -lv cache_armv7 | cut -c 24- | tail +5 | while read line ;
do jtool -extract $line cache_armv7 ; done
Putyourseat-belt• Fourth Obstacle The binary contains in its entitlement the sandbox profile ‘seat-belt’,
which is a kernel extension that restricts a set of features from being used for some processes.
• Workaround Use ldid utility to extract the entitlements and modify the ‘seat-belt’ field of a binary.
• Goal The ability to attach cycript to the process and dump the information from the variables and modify its behavior at runtime
<key>seatbelt-profiles</key><array> <string>seld</string></array>
<key>tlebtaes-profiles</key><array> <string>seld</string></array>
ThugLife
TouchIDSecurity“The resulting map of nodes is stored without any identity information inan encrypted format that can only be read by the Secure Enclave, and is
never sent to Apple or backed up to iCloud or iTunes.”
Partially true
EnablingTouchIDDebugLog• biometrickitd binary contains a string
reference to ‘/var/mobile/Library/Logs/CrashReporter/BioLog’. Such file is generated by the class ‘BioLog’ which is disabled by default
• Save the following ‘com.apple.biometrickitd.plist’ file under the ‘/Library/Managed Preferences/mobile/‘ path.
<?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>debugLogEnabled</key><true/>
</dict></plist>
EnablingTouchIDDebugLog
EnablingTouchIDDebugLog
Binaries&methods• iOS 8.0 headers available at: http://developer.limneos.net/
• Most interesting binaries:• Biometric operations - BiometricKit.framework, biometrickitd,
Preferences.app• NFC Controller - nfcd, NearField.framework, libnfshared.dylib,
PN548_HAL.dylib, PN548_API.dylib, PN548.dylib• Secure enclave - seld, seputil binary (https://theiphonewiki.com/wiki/
Seputil)
BiometricKitIdentityRepresents the enrolled fingerprints on the device. Properties for the
user-defined name and UUID are available.
BLTemplateListRetrieves the template associated to each identity enrolled into the device
TemplateInfoRetrieves information associated to each Template that represents the fingerprint.
BioLogBaseContains all the logs dumped for the TouchID component
BiometricKitXPCServer
TemplateList.cat• Located at /private/var/root/Library/Catacomb/
TemplateList.cat
• Is the template that contains all the information about the fingerprints added into the system.
• Some information is readable, but most interesting one is Base64 encoded and encrypted (?)
TemplateList.cat
GottaCatch’emall!• decodeCatacombDataV1• pullDebugImageData• pullImageMetadata• pullMatchTopologyData• setAppleMesaSEPLoggingLevel• getData / readBinary / getApplications / getCertificates• decodeRootSecurityDomainResponse / dumpAppData
TouchIDimplementationcaveats
LocalAuthentication
Application LocalAuthentication
TouchID
Cred. Management
User Space Operating System Secure Enclave
LASecurity
• LocalAuthentication Trust the OS• Keychain Trust the Secure Enclave
No direct access to secure enclaveNo access to registered fingersNo access to fingerprint image
• Shared Libraries Check with Otool if LocalAuthentication.framework is present.
• canEvaluatePolicy Preflights an authentication policy to see if its possible for authentication to succeed.
• evaluatePolicy Evaluates the specified policy.Block that evaluates a boolean statement.
• Policy LAPolicyDeviceOwnerAuthenticationWithBiometricsNo passcode authenticationFallback to application’s own password entry UI
LocalAuthenticationAPI
TouchIDAuthentication- (void)evaluatePolicy{ LAContext *context = [[LAContext alloc] init]; __block NSString *msg; // show the authentication UI with our reason string [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:NSLocalizedString(@“8=====D~", nil) reply: ^(BOOL success, NSError *authenticationError) { if (success) { msg =[NSString stringWithFormat:NSLocalizedString(@"EVALUATE_POLICY_SUCCESS", nil)]; } else { msg = [NSString stringWithFormat:NSLocalizedString(@"EVALUATE_POLICY_WITH_ERROR", nil), authenticationError.localizedDescription]; } [self printResult:self.textView message:msg]; }];}
TangoDowncarapene:~ root# cycript -p PID
cy# @import com.saurik.substrate.MScy# var oldm = {}cy# MS.hookMessage(LAContext, @selector(evaluatePolicy:localizedReason:reply:),
function(self, reason, block) { block(YES, nil); }, oldm);
Demo#1
What’soutthere?
Tamperingthebinary
NOP ALL THE THINGS
Demo#2
ItsMagic
• ApplePay technology is pretty solid, and well structure, maybe not all the statements made by Apple are true, but the global security deployed is robust.
• A jailbroken device is required to at least scratch the surface, and even with that, the information obtained is not highly sensitive.
• TouchID integration works better with Keychain ACLs, the integration with LocalAuthentication.framework is not recommended to protect your assets.
Conclusions
ThankYouspecial thanks to @abelenko, @trufae (pancake), @revskills (F. Alonso) and J. Levin
(@technologeeks)
Sebas Guerrero @0xroot
Top Related