Securing android applications

  • View
    178

  • Download
    5

Embed Size (px)

DESCRIPTION

Securing android applications

Text of Securing android applications

  • 1. SECURINGANDROIDAPPLICATIONS October 2014

2. http://www.linkedin.com/jmortega1https://speakerdeck.com/jmortega/@jmortegac 3. ARCHITECTURE / DALVIK VM / SANDBOXANDROID APPLICATIONS / PERMISSIONSUTILS EXECUTION ENVIRONMENTTOOLS ECLIPSE / ANDROID STUDIOCOMPONENTS SECURITY / STATIC ANALYSISENCRYPTION / OBSFUSCATIONREVERSING APK TOOLSAPK ANALYZERS / PENTESTING / FORENSICS 4. Android Architecture 5. Dalvik VMREGISTER-BASED VIRTUAL MACHINERUN ON A SLOW CPU WITH LITTLE RAMOPTIMIZED FOR MOBILE DEVICESDEX(Dalvik executable) 6. Dalvik vs ART(4.4)DALVIKARTJust-In-Time (JIT) CompilationAhead-Of-Time (AOT) CompilationCache builds up over timeBoot times are fasterCache is built at first boot Rebooting device takes significantly longerApps compiled when executedStores Compiled AppsConsumes much more internal storage spaceSettings>Developer options>Select runtime 7. SandboxEach app gets a unique linux ID(uid) and Groud ID(gid)Gets own dedicated process and dedicated dalvik VMApplications are "self-signed" with certificate signed by DeveloperApps can share the data with other apps using content providersPermissions determine the capacity for communication componentsThe App Data gets stored in /data/data/ accessible only by UID and GID(root exceptional) 8. /data/dataApps installed by userApps installed by google default : play store, play music , mapsApps that are manufacturer specific : HTC sense, touchwizApps that are shipped with stock rom : browsersROOT 9. Android Applications 10. APK GeneratingZIP + jarsigner+ zipalign for optimizing apk 11. Obtain APKGoogle PlayAlternative markets (BlackMart, Fdroid, Aptoide)Apk extractorhttp://apps.evozi.com/apk-downloader 12. Permissions modelAndroid permissions protectAccess to sensitive APIsAccess to content providersInter- and intra-application communicationProtection mechanism to interact with other applicationsLocation (GPS), Camera, Bluetooth, Telephony, SMS/MMS, Network/dataAndroidManifest.xml 13. Permissions 14. Permissions Be carefull with installapplications Recommend install someapplication to check permissions Disable automatic updates andcheck application permissionsmanually each time an applicationwants to be installed or updated 15. Permissions in appsCheck permissions in runtimePackageManager 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);} 16. Protection levelsnormal: Default level for not application system, always granteddangerous: Higher-Risk permission for access to private data. Requires user approval. SEND_SMS,ACCESS_FINE_LOCATIONsignature Matching signature key. Two apps signed with the same certificatesystem, signatureOrSystem:Same as signature, but also system apps pre- installed like Google Play Services 17. Permissions in appsMinimize requested permissionsUsers like apps that request few permissions33% apps request more permissions that they needGet 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); 18. Permissions in appsApplication don`t need permission to get a camera picWhere is the permission?In the Google Camera ApplicationGoogleCamera.apk 19. Permissions in appsCreate custom permissions 20. Permissions in appsGroup permissions 21. Install in SD CARD$ adb shell$ pm set-install-location 20 [auto]: Let system decide the best location1 [internal]: Install on internal device storage2 [external]: Install on external media 22. Check if Play Store is the installerCheck if Debuggable 23. Check Running emulatorCheck Debugger certificate 24. Check signing key 25. Root detectionprivate boolean isDeviceRooted(){try{Runtime.getRuntime().exec("su");return true;}catch(IOExeception ex){return false;}}public static boolean() isDeviceRooted(){File f= new File("/system/sbin/su");return f.exits();} 26. MalwareInstalling applications from known sitesCheck permissions during installation / upgradeReview comments from usersUpdate the operating system and applications.Disable automatic connection to WiFi networks and avoid connecting to free WiFiDisable BlueTooth when not in useRecommendations to avoid malware 27. Malware detection in Google playBluebox Security ScannerSRT AppScannerLookout Mobile SecurityAdvanced Mobile CareMalwarebytes Anti-MalwareCM Security 28. foresafe.com/scanmobilesandbox.organdrototal.orgcopperdroid 29. Signing applicationsPurpose of certificates in Android is to distinguish application authorsAndroid 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 processesAll applications must be signed with a digital certificate 30. Signing applicationsJava keytool$ keytool -genkey -v -keystore -alias -keyalg RSA -keysize 2048 -validity 10000 31. Sign apk with private keyCheck the apk signaturesm 236 Sun Feb 02 15:08:10 CET 2014 javamail.pop3.providerX.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.MF54279 Sun Feb 02 15:08:10 CET 2014 META-INF/CERT.SF1203 Sun Feb 02 15:08:10 CET 2014 META-INF/CERT.RSAs = signature was verifiedm = entry is listed in manifestk = at least one certificate was found in keystorei = at least one certificate was found in identity scopejar verified.Signing applications$ jarsigner -verify -certs -verbose testing.apk$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore mykeystore testing.apk 32. Android StudioTool included in Android SDK for apk compress and optimizing$ zipalign -f 4 app-signed.apk final-app.apkBuild > Generate Signed APK 33. Eclipse/Android Studio 34. Content ProvidersA specialized type of complex data store in Android to standardize access and manipulation of stored dataBrowser: bookmarks, browse historyCallLog: missed calls, call detailsContacts: Contact detailsMediaStore: Media files 35. Content ProvidersOffers 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 36. Data StorageShared preferencesExternal storageRequires permission android.permission.WRITE_EXTERNAL_STORAGEInternal storageBetter than external since permissions not requiredSqlite3File DataBase with extension *.db stored in /data/data/[package_name]/databasesCloud Google Cloud Messaging(GCM)ROOT 37. Shared preferencesAn xml key-value pairs file stored in /data/data/com.your.package/shared_prefs/preferences.xmlUsed by an application in order to save small sets of data for the applicationStoring sensitive information in shared preferences is not recommendedLibrary for securing shared preferencesEncrypt the key-value pairsAES symmetric keyhttps://github.com/scottyab/secure-preferencesROOT 38. Secure Shared preferencesROOT 39. NetworkingUse HttpsURLConnection for secure web trafficHTTPS + CA Certificateimport javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManagerFactory;// build key store with ca certificateKeyStore keyStore = buildKeyStore(context, certRawResId);// Create a TrustManager that trusts the CAs in our KeyStoreString tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);tmf.init(keyStore);// Create an SSLContext that uses our TrustManagerSSLContext sslContext = SSLContext.getInstance("TLS");sslContext.init(null, tmf.getTrustManagers(), null);// Create a connection from urlRL url = new URL(urlString);HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();urlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); 40. Webviewclass 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) attacksWith JavaScript and Java Reflection can access any of the public methods of the WebAppInterfacesetJavascriptEnabled(true); 41. Webview 42. Webview best practicesDisable JavaScript and Plugin support if they are not needed.Disable local file access. Restricts access to the apps resource and asset directory.Prevent loading content from 3rd party hosts.Activate SSL in activity using HTTPSIn 4.2 @JavascriptInterface method annotation for limit access methods from javascript.Avoid exposing protected data in javascript interface@JavascriptInterfacepublic void method() { dostuff(); } 43. Webview best practicesNot save passwordsNot saving form dataClear CachewebSettings.setSavePassword(false);webSettings.setSaveFormData(false);@Override public void onPageFinished(WebView view, String url) {super.onPageFinished(view, url);view.clearCache(true); //delete local file