The document discusses securing Android applications. It covers the Android architecture, permissions model, data storage, content providers, networking, SQLite encryption, static analysis, and obfuscation. The key topics are the Dalvik VM, sandbox model, permissions, signing applications, minimizing permissions, HTTPS for networking, SQLite encryption, Lint for static analysis, and Proguard for obfuscation.
5. Dalvik VM
REGISTER-BASED VIRTUAL MACHINE
RUN ON A SLOW CPU WITH LITTLE RAM
OPTIMIZED FOR MOBILE DEVICES
DEX(Dalvik executable)
6. Dalvik vs ART(4.4)
DALVIK
ART
Just-In-Time (JIT) Compilation
Ahead-Of-Time (AOT) Compilation
Cache builds up over time
Boot times are faster
Cache is built at first boot Rebooting device takes significantly longer
Apps compiled when executed
Stores Compiled Apps
Consumes much more internal storage space
Settings>Developer options>Select runtime
7. Sandbox
Each app gets a unique linux ID(uid) and Groud ID(gid)
Gets own dedicated process and dedicated dalvik VM
Applications are "self-signed" with certificate signed by Developer
Apps can share the data with other apps using content providers
Permissions determine the capacity for communication components
The App Data gets stored in /data/data/<app process> accessible only by UID and GID
(root exceptional)
8. /data/data
Apps installed by user
Apps installed by google default : play store, play music , maps
Apps that are manufacturer specific : HTC sense, touchwiz
Apps that are shipped with stock rom : browsers
ROOT
13. Permissions model
Android permissions protect
Access to sensitive APIs
Access to content providers
Inter- and intra-application communication
Protection mechanism to interact with other applications
Location (GPS), Camera, Bluetooth, Telephony, SMS/MMS, Network/data
AndroidManifest.xml
15. Permissions
Be carefull with install
applications
Recommend install some
application to check permissions
Disable automatic updates and
check application permissions
manually each time an application
wants to be installed or updated
16. Permissions in apps
Check permissions in runtime
PackageManager pm = context.getPackageManager();
int hasPerm = pm.checkPermission( android.Manifest.permission.WRITE_EXTERNAL_STORAGE, context.getPackageName());
if (hasPerm != PackageManager.PERMISSION_GRANTED) { // do stuff}
private boolean checkWriteExternalPermission(){
String permission = "android.permission.WRITE_EXTERNAL_STORAGE";
int res = getContext().checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
17. Protection levels
normal: Default level for not application system, always granted
dangerous: Higher-Risk permission for access to private data. Requires user approval. SEND_SMS,ACCESS_FINE_LOCATION
signature Matching signature key. Two apps signed with the same certificate
system, signatureOrSystem:Same as signature, but also system apps pre- installed like Google Play Services
18. Permissions in apps
Minimize requested permissions
Users like apps that request few permissions
33% apps request more permissions that they need
Get Camera Pic need android.permission.CAMERA?
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Image capture");
contentValues.put(MediaStore.Images.Media.TITLE, "new image");
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 1);
19. Permissions in apps
Application don`t need permission to get a camera pic
<uses-permission android:name="android.permission.CAMERA" />
Where is the permission?
In the Google Camera Application
GoogleCamera.apk
29. Malware
•Installing applications from known sites
•Check permissions during installation / upgrade
•Review comments from users
•Update the operating system and applications.
•Disable automatic connection to WiFi networks and avoid connecting to free WiFi
•Disable BlueTooth when not in use
Recommendations to avoid malware
30. Malware detection in Google play
Bluebox Security Scanner
SRT AppScanner
Lookout Mobile Security
Advanced Mobile Care
Malwarebytes Anti-Malware
CM Security
33. Signing applications
Purpose of certificates in Android is to distinguish application authors
Android won't allow application to be upgraded unless signed with same certificate the applications are signed with the same key.
Android allows applications that are signed with the same certificate to run in the same processes
All applications must be signed with a digital certificate
35. Sign apk with private key
Check the apk signature
sm 236 Sun Feb 02 15:08:10 CET 2014 javamail.pop3.provider
X.509, CN=Android Debug, O=Android, C=US [certificate is valid from 3/04/13 18:13 to 27/03/43 17:13]
54226 Sun Feb 02 15:08:10 CET 2014 META-INF/MANIFEST.MF
54279 Sun Feb 02 15:08:10 CET 2014 META-INF/CERT.SF
1203 Sun Feb 02 15:08:10 CET 2014 META-INF/CERT.RSA
s = signature was verified
m = entry is listed in manifest
k = at least one certificate was found in keystore
i = at least one certificate was found in identity scope
jar verified.
Signing applications
$ jarsigner -verify -certs -verbose testing.apk
$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore mykeystore testing.apk <alias_name>
36. Android Studio
Tool included in Android SDK for apk compress and optimizing
$ zipalign -f 4 app-signed.apk final-app.apk
Build > Generate Signed APK
40. Content Providers
A specialized type of complex data store in Android to standardize access and manipulation of stored data
Browser: bookmarks, browse history
CallLog: missed calls, call details
Contacts: Contact details
MediaStore: Media files
41. Content Providers
Offers a structured storage mechanism that can be limited to your own application or exported to allow access by other applications.
android:exported =“false"
android:exported ="true"
Versions >= 4.2 exported=“false” by default
<provider android:name=".data.DataProvider"
android:multiprocess="true"
android:authorities="myapp.data.DataProvider"
android:readPermission="myapp.permission.READ"
android:writePermission="myapp.permission.WRITE" />
42. Data Storage
Shared preferences
External storage
Requires permission android.permission.WRITE_EXTERNAL_STORAGE
Internal storage
Better than external since permissions not required
Sqlite3
File DataBase with extension *.db stored in /data/data/[package_name]/databases
Cloud Google Cloud Messaging(GCM)
ROOT
43. Shared preferences
An xml key-value pairs file stored in /data/data/com.your.package/shared_prefs/preferences.xml
Used by an application in order to save small sets of data for the application
Storing sensitive information in shared preferences is not recommended
Library for securing shared preferences
Encrypt the key-value pairs
AES symmetric key
https://github.com/scottyab/secure-preferences
ROOT
45. Networking
Use HttpsURLConnection for secure web traffic
HTTPS + CA Certificate
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
// build key store with ca certificate
KeyStore keyStore = buildKeyStore(context, certRawResId);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
// Create a connection from url
RL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
46. Webview
class WebAppInterface {
private String sensitiveInformation;
public String toString() { return sensitiveInformation; }
}
WebView webview = new WebView(this);
setContentView(webview);
webView.loadUrl("http://website.com");
webView.addJavascriptInterface(new WebAppInterface(this), "injectedObject");
Vulnerability in version 4.1.2(API 16) Jelly Bean in Cross-site scripting (XSS), Cross-site Request Forgery (CSRF) attacks
With JavaScript and Java Reflection can access any of the public methods of the WebAppInterface
setJavascriptEnabled(true);
47. Webview
<script>
function execute(){
var sendSMS=Android.getClass.forName("android.telephony. SmsManager").
getMethod("getDefault",null).invoke(null,null);
sendSMS.sendTextMessage("+323232323",null,"message", null,null);
}
</script>
48. Webview best practices
Disable JavaScript and Plugin support if they are not needed.
Disable local file access. Restricts access to the app’s resource and asset directory.
Prevent loading content from 3rd party hosts.
Activate SSL in activity using HTTPS
In 4.2 @JavascriptInterface method annotation for limit access methods from javascript.
Avoid exposing protected data in javascript interface
@JavascriptInterface
public void method() { dostuff(); }
49. Webview best practices
Not save passwords
Not saving form data
Clear Cache
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
@Override public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.clearCache(true); //delete local files in the browser
}
50. SQLite
SQLiteDatabase db = dbHelper.getWriteableDatabase();
String userQuery = "SELECT lastName FROM useraccounts WHERE userID = ?";
SQLiteStatement prepStatement =db.compileStatement(userQuery);
prepStatement.bindString(1, "userID");
prepStatement.simpleQueryForString();
Prepared statements to avoid sql injection
rawQuery
compileStatement
60. Encryption in phone
Supported since Android 3.0
Encrypts the entire device with AES 128.
Based on dm-crypt implementation
PBKDF2 algorithm for password
Takes at Least 1 h for Encryption of Data.
Denoted to reduce in performance.
61. Encryption in applications
Android Crypto API
Based in javax.crypto from javaSE
Obtain secretKey
public static SecretKey generateKey(char[] password, byte[] salt)
throws Exception {
int iterations = 1000;
int outputKeyLength = 256;
SecretKeyFactory secretKeyFactory
= SecretKeyFactory.getInstance(“PBKDF2WithHmacSHA1”);
KeySpec keySpec = new PBEKeySpec(password, salt,iterations, outputKeyLength);
byte[] keyBytes = secretKeyFactory.generateSecret(keySpec).getEncoded();
return new SecretKeySpec(keyBytes, “AES”);
}
import java.security.*;
import javax.crypto.*;
62. Encryption in applications
public static String encryptText(char[] password, String plainText)
throws Exception {
//Obtain secretkey
SecureRandom secureRandom = new SecureRandom();
int saltLength = 8;
byte[] salt = new byte[saltLength];
secureRandom.nextBytes(salt);
SecretKey secretKey = generateKey(password, salt);
Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);
byte[] initVector = new byte[cipher.getBlockSize()];
secureRandom.nextBytes(initVector);
IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] cipherData = cipher.doFinal(plainText.getBytes(“UTF-8”));
return Base64.encodeToString(cipherData,Base64.NO_WRAP | Base64.NO_PADDING)
+ “]” + Base64.encodeToString(initVector,Base64.NO_WRAP | Base64.NO_PADDING)
+ “]” + Base64.encodeToString(salt,Base64.NO_WRAP | Base64.NO_PADDING);
}
65. Obsfuscation in android projects
Proguard
Integrated in SDK
http://developer.android.com/tools/help/proguard.html
Enable Proguard in eclipse
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.
txt
66. Obsfuscation in android projects
Enable Proguard in android STUDIO
In build.gradle
android { buildTypes { release { runProguard true proguardFile getDefaultProguardFile('proguard-android.txt') , 'proguard-rules.pro' } }
67. Proguard.config
-optimizationpasses 5 -dontusemixedcaseclassnames -dontskipnonpubliclibraryclasses -dontpreverify -verbose -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* -keep public class * extends android.app.Activity -keep public class * extends android.app.Application -keep public class * extends android.app.Service -keep public class * extends android.content.BroadcastReceiver -keep public class * extends android.content.ContentProvider -keep public class * extends android.app.backup.BackupAgentHelper -keep public class * extends android.preference.Preference -keep public class com.android.vending.licensing.ILicensingService -keepclasseswithmembernames class * { native <methods>; } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet); } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet, int); } -keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); } -keep class * implements android.os.Parcelable { public static final android.os.Parcelable$Creator *; }
72. Rename Android app (.apk) to .zip
Extract zip
Run dex2jar on the extracted file
Open the .jar in a java decompiler
Reverse Engineering Android Application
73. Apk Tool
Reverses .apk file to an android project
$ apktool d target.apk output_directory
75. Java vs Smali
Reverses .apk file to an android project
Learning smali through dalvik codes
http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html
93. TraceDroid
http://tracedroid.few.vu.nl
Records the behavior of the executed app, such as its network communication, the UI, but also its internal function calls and Java code that is executed.
Emulates a few actions, such as user interaction, incoming calls and SMS messages, etc. - this will reveal most malicious intents of an app.
94. Pentesting
Virtual Machine with tools for Reverse Engineering
https://redmine.honeynet.org/projects/are/wiki
https://appsec-labs.com/AppUse
Hacking distro dedicated to Mobile forensics and Security