SlideShare a Scribd company logo
Mitigating Data Theft Attack
in Android
By: Rashmi Bhandari
Software Developer
@Visual Infosoft Pvt Ltd, Ahmedabad
Potential Harmful Applications(PHAs)
● Potential security risk
● user and data
● “Malware”
Types of PHAs
● Backdoors
○ Hackers control the device
○ Unauthorized access
● Billing fraud
○ Charges the user
● Spyware
○ Collect personal information from device
○ Commercial spyware
Types of PHAs
● Hostile Downloads
○ download harmful application
● Trojan
○ Perform unpredictable task in the background
● Ransomware
● Rooting
○ Malicious rooting apps
○ Non-malicious rooting apps
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 bmwdept2011@live.com.”
• GPS spoofing Ex:- Pokeman go (lower Android versions 6.0.1)
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.
Mitigating data theft_in_android
Developer has to follow
1) Proguard
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'
}
}
Proguard
• getDefaultProguardFile()
“proguard-android.txt”
“proguard-android-optimize.txt” for more shrinking
“proguard-rules.pro” -> add custom ProGuard rules.
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
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"
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
Stop ignoring Android Lint, use it
• Tool for command line and IDE
• Checks for potential bugs, bad coding habits, broken conventions and much more.
Lint
• Explicitly
On Windows: gradlew lint
On Linux or Mac: ./gradlew lint
• Implicitly
– Analyse -> Inspect code
• 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
Lint
• Configuration
Start in build.gradle by adding the following
lintOptions {
lintConfig file("lint.xml")
}
• Explicitly ignoring some file path.
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
How to check device?
Safety nets
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?
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
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"/>
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.");
}
}
});
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.");
}
}
});
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.
SafetyNet Attestation API
• Check the Google Play services version
if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
== ConnectionResult.SUCCESS)
{
//safety net attestation api call
}
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();
}
}
});
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();
}
});
• 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,
}
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
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>
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...
.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());
}
}
});
How Android Security Works
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.
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
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
Questions?
@bh_rashmi
Thank You

More Related Content

PDF
Web Application Penetration Testing - 101
PPTX
Introduction to Web Application Penetration Testing
PPTX
Hackfest 2019 Talk
PPTX
Why Johnny Still Can’t Pentest: A Comparative Analysis of Open-source Black-b...
PDF
Secure coding presentation Oct 3 2020
PPTX
Why Johnny Still Can’t Pentest: A Comparative Analysis of Open-source Black-b...
PDF
Hacking ingress
PDF
Testing Android Security Codemotion Amsterdam edition
Web Application Penetration Testing - 101
Introduction to Web Application Penetration Testing
Hackfest 2019 Talk
Why Johnny Still Can’t Pentest: A Comparative Analysis of Open-source Black-b...
Secure coding presentation Oct 3 2020
Why Johnny Still Can’t Pentest: A Comparative Analysis of Open-source Black-b...
Hacking ingress
Testing Android Security Codemotion Amsterdam edition

What's hot (20)

PDF
New Era of Software with modern Application Security (v0.6)
PPTX
Security Testing by Ken De Souza
PPTX
nullcon 2011 - Vulnerabilities and Malware: Statistics and Research for Malwa...
PDF
What You Need to Know About Web App Security Testing in 2018
PPTX
Hacker Halted 2014 - Reverse Engineering the Android OS
PDF
Visual Component Testing -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...
PDF
hacking your website with vega, confoo2011
PPTX
Bug Bounty #Defconlucknow2016
PDF
Is My App Secure ?
ODP
Top 10 Web Security Vulnerabilities
PDF
OWASP API Security Top 10 Examples
PDF
[Hands-on] CQRS(Command Query Responsibility Segregation) 와 Event Sourcing 패턴 실습
PDF
Bridging the gap - Security and Software Testing
PDF
Owasp top 10 web application security hazards - Part 1
PPT
香港六合彩
PDF
Windows IR made easier and faster v1.0
PDF
Google+ for Mobile Apps on iOS and Android
PDF
Cross-Platform Authentication with Google+ Sign-In
PDF
Injecting Security into vulnerable web apps at Runtime
PDF
Android Meetup Slovenia #5 - Don't go crashing my heart by Zeljko Plesac, Inf...
New Era of Software with modern Application Security (v0.6)
Security Testing by Ken De Souza
nullcon 2011 - Vulnerabilities and Malware: Statistics and Research for Malwa...
What You Need to Know About Web App Security Testing in 2018
Hacker Halted 2014 - Reverse Engineering the Android OS
Visual Component Testing -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...
hacking your website with vega, confoo2011
Bug Bounty #Defconlucknow2016
Is My App Secure ?
Top 10 Web Security Vulnerabilities
OWASP API Security Top 10 Examples
[Hands-on] CQRS(Command Query Responsibility Segregation) 와 Event Sourcing 패턴 실습
Bridging the gap - Security and Software Testing
Owasp top 10 web application security hazards - Part 1
香港六合彩
Windows IR made easier and faster v1.0
Google+ for Mobile Apps on iOS and Android
Cross-Platform Authentication with Google+ Sign-In
Injecting Security into vulnerable web apps at Runtime
Android Meetup Slovenia #5 - Don't go crashing my heart by Zeljko Plesac, Inf...
Ad

Similar to Mitigating data theft_in_android (20)

PPTX
Hacking mobile apps
PDF
Using the Google SafetyNet API for Banking & Finance
PPTX
Pentesting Android Applications
PPTX
Xamarin Test Cloud - from zero to hero in automated ui testing
PDF
Being Epic: Best Practices for Android Development
PDF
WebAPIs & Apps - Mozilla London
PDF
2012 java one-con3648
PDF
Hacking your Droid (Aditya Gupta)
PDF
Securing Android
PDF
Android_Malware_IOAsis_2014_Analysis.pdf
PDF
Endpoint is not enough
PDF
Attacking and Defending Mobile Applications
PPT
Outsmarting SmartPhones
PDF
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...
PPTX
Android CI and Appium
PPTX
Android Penetration Testing - Day 3
PDF
Mobile Quality Night Vienna 2015 - Testobject Appium in der Cloud
PDF
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...
PPTX
OWASP ZAP Workshop for QA Testers
PPTX
Making Security Agile
Hacking mobile apps
Using the Google SafetyNet API for Banking & Finance
Pentesting Android Applications
Xamarin Test Cloud - from zero to hero in automated ui testing
Being Epic: Best Practices for Android Development
WebAPIs & Apps - Mozilla London
2012 java one-con3648
Hacking your Droid (Aditya Gupta)
Securing Android
Android_Malware_IOAsis_2014_Analysis.pdf
Endpoint is not enough
Attacking and Defending Mobile Applications
Outsmarting SmartPhones
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...
Android CI and Appium
Android Penetration Testing - Day 3
Mobile Quality Night Vienna 2015 - Testobject Appium in der Cloud
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...
OWASP ZAP Workshop for QA Testers
Making Security Agile
Ad

Recently uploaded (20)

PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Cloud computing and distributed systems.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
A Presentation on Artificial Intelligence
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Encapsulation theory and applications.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Cloud computing and distributed systems.
Per capita expenditure prediction using model stacking based on satellite ima...
Network Security Unit 5.pdf for BCA BBA.
Digital-Transformation-Roadmap-for-Companies.pptx
Big Data Technologies - Introduction.pptx
NewMind AI Weekly Chronicles - August'25 Week I
The Rise and Fall of 3GPP – Time for a Sabbatical?
NewMind AI Monthly Chronicles - July 2025
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Advanced methodologies resolving dimensionality complications for autism neur...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
A Presentation on Artificial Intelligence
Spectral efficient network and resource selection model in 5G networks
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Review of recent advances in non-invasive hemoglobin estimation
Encapsulation theory and applications.pdf
MYSQL Presentation for SQL database connectivity
Bridging biosciences and deep learning for revolutionary discoveries: a compr...

Mitigating data theft_in_android

  • 1. Mitigating Data Theft Attack in Android By: Rashmi Bhandari Software Developer @Visual Infosoft Pvt Ltd, Ahmedabad
  • 2. Potential Harmful Applications(PHAs) ● Potential security risk ● user and data ● “Malware”
  • 3. Types of PHAs ● Backdoors ○ Hackers control the device ○ Unauthorized access ● Billing fraud ○ Charges the user ● Spyware ○ Collect personal information from device ○ Commercial spyware
  • 4. Types of PHAs ● Hostile Downloads ○ download harmful application ● Trojan ○ Perform unpredictable task in the background ● Ransomware ● Rooting ○ Malicious rooting apps ○ Non-malicious rooting apps
  • 5. 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 bmwdept2011@live.com.” • GPS spoofing Ex:- Pokeman go (lower Android versions 6.0.1)
  • 6. 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.
  • 8. Developer has to follow 1) Proguard
  • 9. 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' } }
  • 10. Proguard • getDefaultProguardFile() “proguard-android.txt” “proguard-android-optimize.txt” for more shrinking “proguard-rules.pro” -> add custom ProGuard rules.
  • 11. 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
  • 12. 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"
  • 13. 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
  • 14. Stop ignoring Android Lint, use it • Tool for command line and IDE • Checks for potential bugs, bad coding habits, broken conventions and much more.
  • 15. Lint • Explicitly On Windows: gradlew lint On Linux or Mac: ./gradlew lint • Implicitly – Analyse -> Inspect code
  • 16. • 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
  • 17. Lint • Configuration Start in build.gradle by adding the following lintOptions { lintConfig file("lint.xml") } • Explicitly ignoring some file path.
  • 18. 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
  • 19. How to check device?
  • 21. 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?
  • 22. 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
  • 23. 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"/>
  • 24. 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."); } } });
  • 25. 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."); } } });
  • 26. 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.
  • 27. SafetyNet Attestation API • Check the Google Play services version if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS) { //safety net attestation api call }
  • 28. 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(); } } });
  • 29. 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(); } });
  • 30. • 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, }
  • 31. 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
  • 32. 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>
  • 33. 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...
  • 34. .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()); } } });
  • 36. 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.
  • 37. 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
  • 38. 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