Share
Embed
Android Application Security, The Right Way
In this talk you will discover the typical attack surfaces of an Android application. We cover the importance of code protection, implementing secure coding practices, strong crypto implementations, executing in a secure environment and hardening network communications. You will walk away with best practices and common pitfalls to create secure applications.
Dario Incalza
October 28, 2016
Transcript
56 slides
-
@h4oxer • Pre-sales Engineer at GuardSquare • I have opinions
@h4oxer • Like breaking applications • Like securing applications $ whoami -
@h4oxer • Company behind ProGuard and DexGuard • ProGuard is
part of the Android SDK • HQ’s in Leuven, Belgium • @GuardSquare • www.guardsquare.com GuardSquare -
@h4oxer • Attack Surfaces of Apps • Best Practices for
Securing Applications • Cryptography • Code Protection • Secure Communications • Secure Execution Environment • Recap Outline -
Attack Surfaces Application Communication Execution Environment Reverse Engineering Piracy Trojan
Injection Credential Theft Man-in-the- Middle Weak Protocols Debug Analysis Emulator Analysis Hooking Frameworks Rooted Environment Local Data Information Theft Privacy Leaks -
@h4oxer • Static Analysis • APKTool, Smali/Baksmali, BytecodeViewer, JEB ($),
IDA Pro ($$) … • Network Analysis • mitmproxy, charles, burpsuite, wireshark Some Tools -
@h4oxer Some More Tools • Dynamic Analysis • Emulators: Android
Emulator, Genymotion • Hooking Frameworks: • xPosed • Cydia Substrate (old) • Frida (uses JS) • Standard Tools: ptrace, JDB, GDB -
@h4oxer Best Practices • Use secure best coding practices •
Protect, obfuscate and encrypt your application code • Harden your communication • Take into account the execution environment -
@h4oxer Problems • How to store sensitive information on the
device? • How to send sensitive information over the wire? • How to securely generate crypto keys? • How to manage crypto keys? -
@h4oxer Crypto 101 • Symmetric Crypto = one key for
encryption/decryption • AES, 3DES, Blowfish, many more • Public-key Crypto = private and public key • Encrypt with private key, decrypt with public key = digital signatures • Encrypt with public key, decrypt with private key = confidentiality • RSA, ElGamal, ECC, many more -
@h4oxer Generating Secure Keys • Generate symmetric keys on the
device for user-data • A 256 bit AES key derived from a password public byte[] getEncryptionKey(char[] strongPassword){ int iterationCount = 10000; int keyLength = 256; int saltLength = keyLength / 8; // same size as key output SecureRandom random = new SecureRandom(); byte[] salt = new byte[saltLength]; random.nextBytes(salt); KeySpec keySpec = new PBEKeySpec(strongPassword, salt, iterationCount, keyLength); SecretKeyFactory keyFactory = SecretKeyFactory .getInstance(“PBKDF2WithHmacSHA1"); return keyFactory.generateSecret(keySpec).getEncoded(); } -
@h4oxer Securely Manage Crypto Keys 1. Ask for user password
and do not store keys on the device, use PBKDF2 2. Generate keys and store in KeyStore • Vulnerable on rooted devices (hard) 3. Generate keys and store in SharedPreferences • Vulnerable on rooted devices (easy) 4. Use hardcoded key in application code • One key, reverse engineering, key leaked, big problem 5. Store generated key in /sdcard/ • Readable by all apps, stop -
@h4oxer Cryptography • DON’Ts • Hardcoded Crypto Keys • Save
Crypto Keys in /sdcard/ • Log sensitive information • Use AES in ECB mode • Use DES, MD5, it’s broken/weak • Implement DIY crypto • Do not use String objects for sensitive information • Not fixing the SecureRandom vulnerability < Jelly Bean -
@h4oxer • Wrapper for SharedPreferences • Uses AES-128 in CBC
• Option for user supplied password • https://github.com/ scottyab/secure- preferences SecurePreferences SharedPreferences prefs = new SecurePreferences( context, ”userpassword”, ”prefs.xml” ); -
@h4oxer • Virtual Encrypted Disk, encrypted file storage • Clone
of standard java.io.* • Three important methods • VirtualFileSystem.get() • VirtualFileSystem.mount(dbFile, password) • VirtualFileSystem.unmount() • https://guardianproject.info/code/iocipher/ IOCipher -
@h4oxer IOCipher byte[] key = getEncryptionKey(password) VirtualFileSystem vfs = VirtualFileSystem.get();
String path = getDir("vfs", MODE_PRIVATE).getAbsolutePath() + “/container.enc” vfs.createNewContainer(path, key); vfs.mount(path, key); //Start using info.guardianproject.iocipher.* API -
@h4oxer • Uses OpenSSL library • Standard AES-GCM • Small
size, fast performance • Built and used by Facebook • http://facebook.github.io/conceal/ Conceal -
@h4oxer Conceal Example KeyChain keyChain = new SharedPrefsBackedKeyChain(context,CryptoConfig.KEY_256)); Crypto crypto
= AndroidConceal.get().createDefaultCrypto(keyChain); if (!crypto.isAvailable()) { return; } OutputStream fileStream = new BufferedOutputStream( new FileOutputStream(file)); OutputStream outputStream = crypto.getCipherOutputStream( fileStream, Entity.create("entity_id")); outputStream.write(plainText); outputStream.close(); -
@h4oxer Problems • How to make reverse engineering harder? •
How to protect your code against extraction? • How to protect API keys? • How to hide cryptographic operations? -
@h4oxer • Name obfuscation • String encryption • Class encryption
• Resources, asset and native library encryption • Control flow and arithmetic obfuscation • Hide calls through reflection Code Protection -
@h4oxer public String encryptSensitiveMessage() { String nuclearLaunchCode = "abc123"; String
encryptionKey = “secretkey"; return CryptoEngine.encrypt(nuclearLaunchCode, encryptionKey); } For Example -
@h4oxer public String encryptSensitiveMessage() { String nuclearLaunchCode = "abc123"; String
encryptionKey = "secretkey"; Class clazz = Class.forName("CryptoEngine"); Method meth = clazz.getMethod(“encrypt”, String.class, String.class); return (String) meth.invoke(null, nuclearLaunchCode, encryptionKey); } Layer 1 - API Call Hiding -
@h4oxer public String encryptSensitiveMessage() { String nuclearLaunchCode = Base64.decode("YWJjMTIz"); String
encryptionKey = Base64.decode("c2VjcmV0a2V5"); Class clazz = Class.forName(Base64.decode("Q3J5cHRvRW5naW5l")); Method meth = clazz.getMethod(Base64.decode("ZW5jcnlwdA=="), String.class,String.class); return (String) meth.invoke(null,nuclearLaunchCode,encryptionKey); } Layer 2 - String Obfuscation -
@h4oxer public String a() { String a = e.f("YWJjMTIz"); String
b = e.f("c2VjcmV0a2V5"); Class c = Class.forName(e.f("Q3J5cHRvRW5naW5l")); Method d = c.getMethod(e.f(“ZW5jcnlwdA=="), String.class, String.class); return (String) d.invoke(null, a, b); } Layer 3 - Name Obfuscation -
@h4oxer Apply Automatically • ProGuard • Open-source • Name obfuscation
and optimisation • DexGuard • More advanced • Big brother of ProGuard • Backward compatible with ProGuard -
@h4oxer Problems • $ emulator -avd Nexus_5X_API_22 -http-proxy http://localhost:3030 •
$ mitmproxy -p 3030 • Install mitmproxy certificate on emulator -
@h4oxer • A certificate = cryptographically signed identification information •
Certificates are issued by Certificate Authorities (CAs) • Your Android device trusts a number of CAs • SSL validation = check if certificate of server is issued by trusted CA SSL 101 -
@h4oxer SSL Validation Client Server Can you identify yourself? Sure,
I am google.com, here is my certificate! 1. Client checks which CA issued the certificate 2. Do I trust the CA? • Yes, validation is done, connection is trusted. • No A. Is the certificate self signed? Validation failed. B. Is the certificate issued by another CA? Goto 2. -
@h4oxer Thread - MiTM Attack Client Server Identity? Here is
my certificate! • Attacker needs to get a trusted certificate • Hacked CAs: DigiNotar (2011) & Comodo (2011) • Or install his own certificate as trusted • Traffic can be read/altered by MitM MitM Identity? Here is my certificate! -
@h4oxer Protect Against MitM • Android applications by default trust
system CA store • SSL or Certificate Pinning • Option 1: pin on public keys • Option 2: provide your own trust store or certs -
@h4oxer SSL Pinning - OkHttp • https://github.com/square/okhttp OkHttpClient client =
new OkHttpClient.Builder() .certificatePinner(new CertificatePinner.Builder() .add("publicobject.com", "sha256/ afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=") .build()) .build(); -
@h4oxer • Improves network security • Uses best practices for
TLS/SSL • Custom certificate stores from Mozilla and Debian • TOR integration == cool! • https://github.com/ guardianproject/NetCipher NetCipher HTTP Client API NetCipher HttpUrlConnection StrongConnectionBuilder OkHttp3 StrongOkHttpClientBuilder Volley StrongVolleyQueueBuilder Apache StrongHttpClientBuilder StrongOkHttpClientBuilder builder = StrongOkHttpClientBuilder. forMaxSecurity(this) -
@h4oxer • Static code protection leads to dynamic attacks •
Three main attack techniques • Dynamic code injection a.k.a hooking • Attaching debuggers • Memory dumping Problems -
@h4oxer • Tools: XPosed, Frida, Cydia Substrate • Requires rooted
device • Places hooks • E.g., before encryption calls, after decryption calls Dynamic Code Injection -
@h4oxer • Tools: Java Debug Bridge (JDB), Gnu Project Debugger
(GDB) • Inspect code execution, paths, variables • In Android alter AndroidManifest.xml > debuggable=true Debuggers -
@h4oxer • Advanced security tools offer code encryption • Code
available in memory • Dumping memory == getting unencrypted code • Tools: Linux Memory Extractor (LiME) Memory Dumping -
@h4oxer • Application can scan its environment • Should it
run on a rooted device? • Should it run on an emulator - which is rooted by default? • Detect dynamic code injection • Detect application tampering Securing Your Environment -
@h4oxer • Get Google’s opinion on the device status •
Response is JSON Web Signature (JWS) • Developer needs to review response and verify signature • SafetyNetApi.attest() SafetyNet API -
@h4oxer • SafetyNet looks at various device attributes (by @ikoz)
• Installed packages • SU Files • Settings (adb enabled, lock screen enabled, …) • SE Linux state • Device admin blacklist • … SafetyNet API -
@h4oxer • Advantages • Google knows a lot • Updated
remotely • Takes a lot into consideration • Disadvantage • You only get a binary answer: compatible/incompatible • Google Play Services dependency • Network requests take time • Developer needs to verify JWS SafetyNet API -
@h4oxer • Implement strong coding practices and strong cryptography •
Protect code statically through various layers that protect code and each other • Harden the communications • Scan, detect and protect against insecure execution environments Recap -
@h4oxer • https://nelenkov.blogspot.be/2012/04/using-password- based-encryption-on.html • https://koz.io/inside-safetynet/ • https://github.com/scottyab • Android
Hacker’s Handbook • Android Security Internals • www.guardsquare.com References