Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Mitigating data theft attack in android @GDG Ah...

Mitigating data theft attack in android @GDG Ahmedabad

Reducing the data theft in android using verify api and safety net and also explanation about the proguard and lint

Avatar for Rashmi bhandari

Rashmi bhandari

November 18, 2017
Tweet

More Decks by Rashmi bhandari

Other Decks in Technology

Transcript

  1. Mitigating Data Theft Attack in Android By: Rashmi Bhandari Software

    Developer @Visual Infosoft Pvt Ltd, Ahmedabad
  2. Types of PHAs • Backdoors ◦ Hackers control the device

    ◦ Unauthorized access • Billing fraud ◦ Charges the user • Spyware ◦ Collect personal information from device ◦ Commercial spyware
  3. Types of PHAs • Hostile Downloads ◦ download harmful application

    • Trojan ◦ Perform unpredictable task in the background • Ransomware • Rooting ◦ Malicious rooting apps ◦ Non-malicious rooting apps
  4. Real time example • Zeus Banking Trojan Hits Android Phones

    https://www.informationweek.com/mobile/zeus-banking-trojan-hits-android-pho nes/d/d-id/1098909 • Game Dunga http://blog.trendmicro.com/trendlabs-security-intelligence/one-click-billing-fraud- scheme-through-android-app-found/ • “Your mobile number has won £850,000 IN **** Award Promo. Send your name, address and account number to [email protected].” • GPS spoofing Ex:- Pokeman go (lower Android versions 6.0.1)
  5. How google fight with PHAs Chamois Popup ads,boosting app promotion

    by automatically installing other application in the background, subscribing users to premium services by sending text message and downloading plugins without their knowledge.
  6. Proguard buildTypes { debug{ debuggable true minifyEnabled true shrinkResources true

    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } release { debuggable false minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }
  7. Customized proguard rules -keep [,modifier,...] class_specification Ex:-1) -keep public class

    MyClass 2) -keep class com.example.animals.Dog { void barking(); void hungry(); void sleeping() } @keep for annotation
  8. LINT Security checks : • ExportedActivity: Checks for exported activities

    that do not require permissions. • ExportedContentProvider: Checks for exported content providers that do not require permissions • ExportedReceiver: Checks for exported receivers that do not require permissions • ExportedService: Checks for exported services that do not require permissions android:exported="true"
  9. LINT • GrantAllUris: Checks for <grant-uri-permission> elements where everything is

    shared • HardcodedDebugMode : Checks for hard coded values of android:debuggable in the manifest • SetJavaScriptEnabled: Looks for invocations of android.webkit.WebSettings.setJavaScriptEnabled • WorldReadableFiles : Checks for openFileOutput() and getSharedPreferences() calls passing MODE_WORLD_READABLE • WorldWriteableFiles : Checks for openFileOutput() and getSharedPreferences() calls passing MODE_WORLD_WRITEABLE
  10. Stop ignoring Android Lint, use it • Tool for command

    line and IDE • Checks for potential bugs, bad coding habits, broken conventions and much more.
  11. Lint • Explicitly On Windows: gradlew lint On Linux or

    Mac: ./gradlew lint • Implicitly – Analyse -> Inspect code
  12. • By default, lint will break the build on errors,

    but not on warnings, which is why warnings tend to go unnoticed until there’s a build-up of hundreds of them. 1) lintOptions { warningsAsErrors true abortOnError true htmlReport true //locations for the rules and output lintConfig file("${rootDir}/config/lint/lint-config.xml") htmlOutput file("${buildDir}/reports/lint/lint.html") } • warningsAsErrors = true — Consider all warnings as errors • abortOnError = true — break the build on any Lint error • lintConfig — A file which provides input for lint, with definitions per rule
  13. Lint • Configuration Start in build.gradle by adding the following

    lintOptions { lintConfig file("lint.xml") } • Explicitly ignoring some file path.
  14. Security Features 1. Verify apps • Checks users' devices for

    PHAs • Detect PHAs – Warn users – Suggest like twice about downloading a particular app. – Remove the app from their devices entirely
  15. Safety nets • Is the device believed to be rooted?

    • Is the hardware information recognized? Check these many • Is the device monitored? parameters • Is the device infected with malicious apps? • Is the device’s profile recognized?
  16. Safety nets API Types:- SafetyNet Verify Apps API ➢ Interact

    programmatically with the Verify Apps feature on a device. ➢ Protect the app’s data ➢ Google play protect Enabling app verification isVerifyAppsEnabled : - app verification is enabled enableVerifyApps :- requesting for enabling app verification listHarmfulApps :- list of any known potentially harmful apps
  17. Implemetation • Go to google developer console -> Create project

    -> add SHA1 key • Go to library page -> search for “ Android Device Verification API” • If the API isn't already enabled, click Enable. • <meta-data android:name="com.google.android.safetynet.ATTEST_API_KEY" android:value="@string/api_key" /> • implementation 'com.google.android.gms:play-services-safetynet:11.6.0‘ • <uses-permission android:name="android.permission.INTERNET"/>
  18. isVerifyAppsEnabled() SafetyNet.getClient(this) .isVerifyAppsEnabled() .addOnCompleteListener(new OnCompleteListener<SafetyNetApi. VerifyAppsUserResponse>() { @Override public void

    onComplete(Task<SafetyNetApi.VerifyAppsUserResponse> task) { if (task.isSuccessful()) { SafetyNetApi.VerifyAppsUserResponse result = task.getResult(); if (result.isVerifyAppsEnabled()) { tvData.setText("The Verify Apps feature is enabled"); } else { tvData.setText("The Verify Apps feature is disabled"); } } else { tvData.setText("A general error occurred."); } } });
  19. enableVerifyApps() SafetyNet.getClient(this) .enableVerifyApps() .addOnCompleteListener(new OnCompleteListener<SafetyNetApi.VerifyAppsUserResponse>() { @Override public void onComplete(Task<SafetyNetApi.VerifyAppsUserResponse>

    task) { if (task.isSuccessful()) { SafetyNetApi.VerifyAppsUserResponse result = task.getResult(); if (result.isVerifyAppsEnabled()) { Log.d("MY_APP_TAG", "The user gave consent " + "to enable the Verify Apps feature."); tvData.setText("The user gave consent to enable the Verify Apps feature."); } else { Log.d("MY_APP_TAG", "The user didn't give consent " + "to enable the Verify Apps feature."); tvData.setText("The user didn't give consent " + "to enable the Verify Apps feature."); } } else { Log.e("MY_APP_TAG", "A general error occurred."); tvData.setText("A general error occurred."); } } });
  20. SafetyNet Attestation API 1. Call the attestation api 2. API

    request a signed response 3. Backend sends the response to Google Play services. 4. signed response is returned to app. 5. App forward the signed response. 6. server verifies the response and sends the result of the verification process back to your app.
  21. SafetyNet Attestation API • Check the Google Play services version

    if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS) { //safety net attestation api call }
  22. SafetyNet.SafetyNetApi.attest(mGoogleApiClient, nonce) .setResultCallback(new ResultCallback<SafetyNetApi.AttestationResult>() { @Override public void onResult(@NonNull SafetyNetApi.AttestationResult

    attestationResult) { Status status = attestationResult.getStatus(); if (status.isSuccess()) { String jwsResult = attestationResult.getJwsResult(); Log.v("jwsResult",jwsResult); verifyOnline(jwsResult); } else { Toast.makeText(MainActivity.this, "Error !", Toast.LENGTH_SHORT).show(); } } });
  23. Retrofit retrofit = new Retrofit.Builder() .baseUrl(GOOGLE_API_VERIFY_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); RetrofitInterface retrofitInterface

    = retrofit.create(RetrofitInterface.class); JWSRequest jwsRequest = new JWSRequest(); jwsRequest.setSignedAttestation(jws); Call<Response> responseCall = retrofitInterface.getResult(jwsRequest, getString(R.string.api_key)); responseCall.enqueue(new Callback<Response>() { @Override public void onResponse(Call<Response> call, retrofit2.Response<Response> response) { Log.v("response",response.body().toString()); boolean result = response.body().isValidSignature(); if (result) { decodeJWS(jws); } else { Toast.makeText(MainActivity.this, "Verification Error !", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Response> call, Throwable t) { Log.d(TAG, "onFailure: " + t.getLocalizedMessage()); Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } });
  24. • getJwsResult() :- JSON Web Signature (JWS) represents content secured

    with digital signatures or Message Authentication Codes (MACs) using JavaScript Object Notation (JSON) based data structures. { "nonce": "R2Rra24fVm5xa2Mg", // its 16 bits of data "timestampMs": 9860437986543, "apkPackageName": "com.package.name.of.requesting.app", "apkCertificateDigestSha256": ["base64 encoded, SHA-256 hash of the certificate used to sign requesting app"], "apkDigestSha256": "base64 encoded, SHA-256 hash of the app's APK", "ctsProfileMatch": true, "basicIntegrity": true, }
  25. ctsProfileMatch = profile of the device running on the app

    matches the profile of a device that has passed Android compatibility testing. basicIntegrity the value of basicIntegrity is true, then the device running your app likely wasn't tampered with, but the device hasn't necessarily passed Android compatibility testing. apkPackageName,apkCertificateDigestSha256,apkDigestSha256 :- provide information of the apk and use to verify the identity of the calling app
  26. SafetyNet reCAPTCHA API Saftynet api + reCAPTCHA API = malicious

    traffic • minSdkVersion to 14 or higher • verifyWithRecaptcha() • https://www.google.com/recaptcha <activity android:name=".SaftynetRecaptcha"> <meta-data android:name="com.google.android.safetynet.ATTEST_API_KEY" android:value="@string/recaptcha_key" /> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
  27. SafetyNet.getClient(this).verifyWithRecaptcha(getString(R.string.recaptcha_key)) .addOnSuccessListener( this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() { @Override public void onSuccess(SafetyNetApi.RecaptchaTokenResponse

    response) { // Indicates communication with reCAPTCHA service was // successful. String userResponseToken = response.getTokenResult(); Log.v("userResponseToken",userResponseToken); if (!userResponseToken.isEmpty()) { // Validate the user response token using the // reCAPTCHA siteverify API. } } }) Continue...
  28. .addOnFailureListener( this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception

    e) { if (e instanceof ApiException) { // An error occurred when communicating with the // reCAPTCHA service. Refer to the status code to // handle the error appropriately. ApiException apiException = (ApiException) e; int statusCode = apiException.getStatusCode(); Log.d(TAG, "Error: " + CommonStatusCodes .getStatusCodeString(statusCode)); } else { // A different, unknown type of error occurred. Log.d(TAG, "Error: " + e.getMessage()); } } });
  29. Storing the data Internal storage • Files saved to the

    internal storage are private to your application and cannot be accessed by the other application • Not to use MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE • Share the content of your files with other apps you should use a Content Provider.
  30. External storage • Files created on external storage are world

    readable and writeable • Even external storage can be removed from the device and connected any other device like computer. • Don't store executables or class files on external storage . • Perform input validation while handling data from external storage
  31. Content Provider • Limited to access for the same application

    • Exported to allow access by other application . Syntax : android : exported =true • When exported =false <permission android:name="com.example.android.safetynet.MainActivity" android:protectionLevel="signature"/> • Signature don't require user permission