Upload
dataart
View
196
Download
2
Embed Size (px)
Citation preview
Security in mobile appsYAROSLAV VORONTSOV, MOBILE SOFTWARE ARCHITECTJULY 14, 2016
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS" 2
Agenda•Introduction• Theoretical base• Terms
•Security whitepaper overview• Hardware features• Software features
•How to attack iOS applications
•Protection mechanisms overview• Ciphers (Security framework, ex-Common Crypto)• TLS and ATS
•Recipes
•Other materials
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 3
IntroductionESSENTIALS FOR DEEP UNDERSTANDING OF SECURITY MECHANISMS
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 4
Theoretical base•Probability theory and random processes• Negligibility
•PRNG• Hardware vs Software
•Crypto algorithms• OTP (Vernam) • PRF and PRP• Symmetric encryption• Asymmetric encryption• Hashes and MACs• Attacks on encryption
•Network and telecommunications• ISO/OSI stack: session level – SSL and TLS
•Key generation/distribution schemes• Diffie-Hellmann protocol• Kerberos
•Trust and certificates• Public and private keys
•Documents• PKCS – Public Key Cryptography Standards• RFC – Request For Comments
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 5
Terms Identification – providing evidences of an identity
Authentication – validation of identity
Authorization – check of privileges
2FA/MFA – two-/multi-factor authentication
UID/GID – User/Group ID
Key wrapping – Encryption of an encryption key
MDM – Mobile Device Management
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 6
Security Whitepaper overviewSEPTEMBER 2015 VERSION
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 7
Main document iOS Security Guide, Sep. 2015
We’re going to talk about:◦ Boot process◦ Secure Enclave◦ System Software Authorization◦ Passcode and Touch ID policies◦ AES hardware acceleration◦ Data protection classes◦ Keychain protection◦ Key bags◦ Other important features
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 8
Boot process and SSA
BootROM LLB iBoot Kernel
NAND memory
Apple’s root CA key Apple SSA Server
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 9
Secure Enclave (Apple A7+ only)•Available for A7 CPU family and above, works as co-processor
•Built-in hardware PRNG
•Communicates with CPU via Mailbox (write-only) and encrypted shared memory (read-only)
•Responsible for• Passcode and Touch ID• Data protection classes
•Updates its firmware independently
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 10
Passcode and Touch ID (iOS 9+)•Three main policies defined• 4-digit passcode• 6-digit passcode• Alphanumeric of arbitrary length
•Checks take 80ms
•Interval is increased after N failed attempts
•Max 5 fingers for Touch ID
•Touch ID – 5 mandatory cases for passcode input
•Wipe after 10-12 failed attempts
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 11
Hardware-accelerated encryption
AES crypto engine is hardware-accelerated, implemented in silicon and has direct memory access
Chip has two keys embedded – UID and GID◦ User ID is unique for a device◦ Group ID is unique for a family of devices (with
the same CPU)◦ Keys are not leaving crypto engine
However, these keys could be compromised on a jailbroken device by patching aes_decrypt() function in iBoot bootloader (read here)
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 12
File protection classesClass name Description Key derivation and wrapping
NSFileProtectionComplete Files are available only if the device is unlocked
Class key protected with a key derived from the passcode and device UID
NSFileProtectionCompleteUnlessOpen
Some files can be written even if the device is locked
Asymmetric crypto is used, file key is protected using One-Pass Diffie-Hellman Key Agreement
NSFileProtectionCompleteUntilFirstUserAuthentication
Default class for all 3rd party apps. Files are unavailable until user enters passcode
Behaves like NSFileProtectionComplete, except the fact that key is not wiped during reboot
NSFileProtectionNone No protection available Class key is protected only with the device UID and stored in Effaceable storage
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 13
File encryption mechanism•Per-file encryption – each file has its own encryption key
•Encryption key (AES256-CBC) is generated by data protection engine
•Key is wrapped using file protection class key
•Key and SHA1 hash are stored in file’s metadata
•Metadata is encrypted using FS key which is created during system installation/reset
•When file is accessed, its key is unwrapped and used for AES decryption
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 14
Key bags• System
• Always accessible (no protection)
• iTunes Backup• Backup password
• Escrow• Key stored in MDM
• iCloud• Same as Backup, but uses
asymmetric cryptography
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 15
Other out-of-box features Code signing – iOS verifies the digital signatures of all binaries containing executable code
Sandboxing – iOS applications are isolated from each other
Least available privileges – iOS applications are running under a user’s account with the least possible privileges
Entitlements – control access to hardware and software features
ASLR – preventing exploits. On by default, compile-time feature
XN – Execute Never flag for all memory pages except those passed signature checks
Access limitation – user should explicitly confirm access to Contacts, Calendars, Reminders, Photos, motion data, social media, microphone, camera, Home and Health kits, Bluetooth sharing
Extensions – they inherit all the access rights from their parent applications. (KEYBOARDS!!!)
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 16
ASLR and PIE
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 17
Attacking iOS appsBASED ON OWASP CHEAT SHEET
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 18
Vectors of attack
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 19
Toolkit of a penetration testerTool Link Description
CharlesBurp
http://www.charlesproxy.com/http://www.portswigger.net/burp
HTTP and HTTPS proxy servers
OpenSSH http://www.openssh.com/ Connect to the iPhone remotely over SSH
SQLite 3 http://www.sqlite.org/ SQLite Database Client
GDB http://www.gnu.org/software/gdb/ GNU Debugger
otool man otool Displaying binary information
sysctl man sysctl Read/manage kernel parameters
cycript http://www.cycript.org/ JS-based language to attack runtime
Mallory http://intrepidusgroup.com/insight/mallory Proxy for binary protocols
Wireshark https://www.wireshark.org/ Sniffer
re_tools https://github.com/emonti/iOS_app_re_tools Reverse engineering tools for iOS apps
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 20
Protection mechanisms overviewCOMMON CRYPTO, APP TRANSPORT SECURITY
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 21
API Security framework (C API)
◦ Common Crypto library which contains an implementation of the most common symmetric & asymmetric ciphers and hashes. Uses CC- function prefixes.
◦ Keychain API – secure storage for credentials. SecItem- functions or Obj-C/Swift wrappers.◦ Certificate management – SecCertificate-, SecTrust- functions.◦ SSL3.0/TLS1.0 connection management. Should not be used!
OpenSSL (C API)◦ Avoid the versions which are known to be vulnerable. Keep in mind licensing issues.
The worst idea ever is to implement all encryption and decryption by yourself◦ You’re re-inventing the wheel◦ Your implementation is vulnerable to all kinds of attacks – theoretical and practical
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 22
Keychain and Keychain API Designed for
◦ Passwords and tokens◦ Certificates and public/private keys◦ Application codes and receipts
Data sharing◦ Requires kSecAttrAccessGroup◦ Depends on Bundle ID◦ Entitlements – keychain-access-groups,
application-identifier, application-group
Plain C API, lots of wrappers available
Works via keychaind, queries via dictionaries
Keychain management functions◦ SecItemCopyMatching()◦ SecItemDelete()◦ SecItemUpdate()◦ SecItemAdd()◦ NEW: SecAccessControlCreateWithFlags() – used
with kSecAttrAccessControl attribute in SecItemAdd()
Record types◦ kSecClassGenericPassword◦ kSecClassInternetPassword◦ Certificates and keys are also supported!
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 23
Keychain items – Protection classes
Class name File system analog Availability
kSecAttrAccessibleWhenUnlocked NSFileProtectionLevelComplete When unlocked
N/A NSFileProtectionCompleteUnlessOpen While locked
kSecAttrAccessibleAfterFirstUnlock NSFileProtectionCompleteUntilFirstUserAuthentication After first unlock
kSecAttrAccessibleAlways NSFileProtectionNone Always
kSecAttrAccessibleWhenPasscode SetThisDeviceOnly
N/A Passcode enabled
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 24
Example of full dump of keychainFoundstone iOS Keychain analyzer
Available on GitHub
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 25
Keychain requestsSecure Enclave, keychaind and others
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 26
Common Crypto API (plain C API) No Apple Developer documentation, use man CC_crypto, CC_MD5, CC_SHA, CCHmac, CCCryptor
CCCryptor – API for usage of symmetric block and stream ciphers. Supports DES, 3DES, AES◦ CCCryptorCreate/CCCryptorCreateFromData + CCCryptorReset + CCCryptorRelease◦ CCCryptorUpdate (N times, padding!) + CCCryptorFinal (block ciphers)◦ CCCryptorGetOutputLength (required buffer size) + CCCrypt (one-time encryption for small input)
CCHmac – API for usage of hashing and message authentication codes◦ kCCHmacAlgSHA1 and kCCHmacAlgMD5 – legacy◦ kCCHmacAlgSHA2 (224, 256, 384, 512) – modern
CC_MD5 and CC_SHA◦ Access to MD2, MD4, MD5 for compatibility◦ Access to SHA1 for compatibility and SHA2 modern hashes
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 27
Other Security APIs CCKeyDerivationPBKDF
◦ Password-based key derivation function v2◦ Number of rounds can be tweaked via CCCalibratePBKDF
SecRandomCopyBytes◦ Use this function to get a sequence of pseudo-random bytes◦ Or read directly from /dev/random (on OS X only)◦ FORGET ABOUT RAND(), SRAND() AND ARC4RANDOM()!!!◦ Look right to understand why they’re bad
SSLContextRef and manipulating functions◦ Implementation of SSL 3.0 and TLS 1.0◦ DO NOT USE THIS!!!
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 28
TLS: handshake• TCP handshake
• TLS handshake
• Certificate validation
• Cipher suites exchange
• Encryption key derivation
• Transferring encrypted data
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 29
TLS: Certificate chainsAka “Chains of trust”
If certificate’s private key has been stolen, there’s a revocation procedure
2 mechanisms of revocation checks
• CRL – Certificate Revocation list
• OSCP – Online Cert Status protocol
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 30
ATS and its requirements ATS is switched on by default and forces the developers to follow security best practices
ATS-readiness can be checked and diagnosed using◦ nscurl utility (OS X 10.11 and above) – nscurl –ats-diagnostics [—verbose] URL◦ CFNETWORK_DIAGNOSTICS=1 launch argument for an iOS application
Specifies the following requirements for the connection (and for the server):◦ Server leaf certificate signed by a CA whose certificate is incorporated into the OS/trusted root CA◦ Minimal TLS protocol version is 1.2◦ Non-compromised block/stream cipher◦ SHA2 family of hashes (SHA256, SHA384, SHA512) used for MACs (Message Authentication Codes)◦ RSA with long key (over 2048 bits) or ECDSA (over 256 bits) for digital signatures◦ Perfect forward secrecy required for key exchange protocol (ECDHE)
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 31
Secrecy and perfect forward secrecy
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 32
Cipher suites supporting PFS
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
If PFS is disabled, ATS will support some more ciphers:
TLS_RSA_WITH_AES_256_GCM_SHA384
TLS_RSA_WITH_AES_128_GCM_SHA256
TLS_RSA_WITH_AES_256_CBC_SHA256
TLS_RSA_WITH_AES_256_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA256
TLS_RSA_WITH_AES_128_CBC_SHA
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 33
ATS: exceptions Configured via NSExceptionDomains dictionary where keys are domains themselves and values are dictionaries
◦ NSIncludesSubdomains◦ NSExceptionAllowsInsecureHTTPLoads/NSThirdPartyExceptionAllowsInsecureHTTPLoads◦ NSExceptionRequiresForwardSecrecy/NSThirdPartyExceptionRequiresForwardSecrecy◦ NSExceptionMinimumTLSVersion/NSThirdPartyExceptionMinimumTLSVersion
ATS completely switched off by specifying NSAllowsArbitraryLoads key and YES value◦ When to use: IP addresses used instead of FQDN◦ When to use: functionality of unlimited web browsing via UIWebView or WKWebView
NSAllowsArbitraryLoads is compatible with NSExceptionDomains (see Examples there)◦ ATS policies will be still applied to domains configured via NSExceptionDomains◦ If ATS is disabled, standard HTTPS validations are still performed
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 34
Classic way of certificate validation•NSURLConnection/NSURLSession receives NSURLAuthenticationChallenge
•Challenge has an instance of NSURLProtectionSpace which allows to determine authentication method. In case of TLS connection:• the method will be ServerTrust;• serverTrust property will contain a SecTrustRef reference. It contains the certificate information.
•The algorithm is simple: set policy and validate server trust• You can validate fingerprints of the certificates (“lightweight” pinning). Use SecCertificate... functions
•You can choose between SSL validation policy, basic X509 policy and revocation list policy
•You can choose between pinned and system certificates (SecTrustSetAnchorCertificates/Only)
•Call SecTrustEvaluate/Async and check the result – it should be either Proceed or Unspecified
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 35
RecipesWHAT YOU CAN DO TO PROTECT AGAINST THREATS
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 36
Securing your cached data If you use Core Data
◦ Use NSValueTransformer. Problem: global key declaration◦ Use transient properties. Problem: no full-text search
If you use SQLite◦ SQLCipher◦ SEE
If you use any other kind of file◦ Assign this file to a sufficient protection class◦ Use AES encryption before writing file contents to the disk
If you want to save credentials◦ Encrypted, salted and hashed in Keychain◦ Use steganography, Luke)
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 37
Web view and caching web content
You have a tough choice: WKWebView vs UIWebView vs SFSafariViewController◦ Good old UIWebView is affected by global HTTP cache policy◦ Modern WKWebView is generally safer – it’s running in an external process◦ Fresh SFSafariViewController requires no ATS tweaks to support arbitrary web content◦ Comparison of WKWebView and UIWebView, WKWebView tips
Configure HTTP headers for cache management wisely!◦ Client side caching with examples◦ A beginner’s guide to HTTP Cache headers
NSURLCache + NSHTTPCookieStorage vs. WKWebsiteDataStore◦ Clean up everything which may be sensitive◦ Clean up personal data after logout◦ Grab/set cookies manually using JavaScript controllers for WKWebView. Yes, it’s painful
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 38
How to get a good encryption key?
Key should be both device- and user-dependent
DO NOT◦ Use your password or hash(password) as a key◦ Rely only on device-stored or device-specific information◦ Cache the calculated key anywhere, even in memory
DO (3-2-1 principle)◦ Use password-based key derivation functions (PBKDF2 at the moment)◦ Use multiple iterations of hash/key derivation function◦ Use graphical pattern/secure PRNG to derive a part of your key◦ Split the arguments of your KDF and store them in different places◦ Use salt to make it harder to crack the key
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 39
How not to lose your encrypted data?
You derived your SDEK (sensitive data encryption key) directly from your password using PBKDF2 and... you’re going to apply a password change policy as well.
This means that you’re going to lose you cached data
The best idea is described on TechNet. A modified algorithm is described below:◦ Create a random content encryption key (CEK)◦ Encrypt the file and save encryption IV and nonce in metadata◦ Wrap CEK with Key Encryption Key (KEK). KEK is derived using PBKDF2◦ The result is called Data Decryption Field (DDF). DDF is stored in metadata as well◦ When password is changed, DDF is decrypted using the result of PBKDF2(old) and re-encrypted with
PBKDF(new)◦ An alternative variant is to use asymmetric cryptography – public key for CEK encryption and private key
for DDF decryption. In such case, private key should be wrapped using PBKDF2 results
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 40
Building secure authentication scheme•Do not transfer passwords• Unencrypted• Weakly encrypted• Hashed few times
•Use tokens/session IDs with limited TTL
•Avoid token persistence
•Prevent stealing session ID and fixation attacks
•Even if a request has been intercepted• Resistance against replay attack• Resistance against brute-force attack
•Use digest authentication
•Use session IDs
•Use nonce values
•Use expiration periods for tokens and nonce values
•Let users identify their “trusted” locations and warn users via a side channel (i.e., SMS codes) if there’s an attempt to authenticate from a suspicious or untrusted location
•Supply only a generic information about authentication failures to users
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 41
And something more…•Use ptrace() to catch and deny debuggers in Release mode
•Clean Pasteboard while going into background
•Forbid auto-correction for “sensitive” text fields
•Introduce password characters and password expiration policies
•Cover views with splash screen/image to prevent sensitive information appearance on snapshots
•Use 2FA/MFA – send SMS and/or use special code generation apps like Google Authenticator and/or hardware tokens and/or API keys
•“Lock” application or perform logout after a predefined period of inactivity
•Remember: it’s better to protect against particular threats rather than “improve security level” in general
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 42
Keep this in mind! If you’re using non-public domain implementation of encryption algorithms, you’re responsible for its registration in CCATS (Bureau of Industry and Security)
◦ Read this article for more details
Fortunately, iTunes Connect allows you selecting one of predefined options during the binary submission
◦ Personal data, including biometric and health stats◦ Network connections◦ Banking transactions and credit card data
Even implicit usage of encryption (via SQLCipher or HTTPS connections) makes you answer “YES” in iTunes Connect
Contact Apple Support DIRECTLY in case of issues with “crypto” app submission
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 43
Other materialsWHERE TO GO FURTHER
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 44
Other materials•Useful web links• PKCS – Public Key Cryptography Standards• iOS Encryption• Аутентификация в веб-приложениях• iOS Developer Cheat Sheet from OWASP
•DataArt materials• Crypto-ликбез• Security in iOS Apps (v1)• iOS Penetration testing
•Books• J. Zdsiarski. Hacking and securing iOS Applications
•Security course coming soon!
•Watch WWDC videos
WWDC 2010◦ Session 209 – Securing your application data
WWDC 2011◦ Session 202 – Security overview◦ Session 208 – Securing iOS Applications
WWDC 2012◦ Session 704 – The Security Framework
WWDC 2013◦ Session 709 – Protecting Secrets with the Keychain
WWDC 2014◦ Session 711 – Keychain and Authentication with Touch ID
WWDC 2015◦ Session 706 – Security and your apps
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 45
Other materials More web links
◦ Яблочный Forensic◦ Что такое TLS◦ Можно ли украсть деньги из мобильного банк
инга?◦ Вы опасно некомпетентны в криптографии◦ Криптография побочных эффектов◦ iOS App Security◦ Zdziarski Blog◦ HTTP Server trust evaluation◦ SSL Pinning with self-signed certificates◦ Penetration testing for iPhone applications
…And even more web links…◦ App Transport Security◦ Анализ SSL/TLS трафика в Wireshark◦ TN2232: Server Trust Evaluation◦ iPhone Forensics: Analysis of iOS Backups◦ Password storage cheat sheet◦ How to store salt correctly (v1)?◦ How to store salt correctly (v2)?◦ Changing passwords when files are encrypted wi
th PBKDF2-derived key◦ PBKDF2 and password history◦ Salted password hashing – doing it right
01.05.2023 Y. VORONTSOV "SECURITY IN IOS APPS V2" 46
Thank you!Your questions, please