SlideShare a Scribd company logo
CNIT 128
Hacking Mobile Devices
9. Writing Secure 

Android Apps
Common Vulnerabilities
• Code injection
• Logic flaws
• Insecure storage
• Application configuration
• Insecure communication
• Logging
Topics
• Principle of Least Exposure
• Essential Security Mechanisms
• Advanced Security Mechanisms
• Slowing Down a Reverse Engineer
Principle of Least Exposure
Minimizing Attack Surface
• Find all entry points
• Code exposed to inputs from outside
sources
• Remove unnecessary entry points
• Perform security checks at necessary entry
points
App Components
• Don't export more components than required
• The safest case is shown below
• Most apps require some integration with other apps
Data Storage
• Avoid storing unnecessary data
• Such as passwords!
• Private directory is protected somewhat by the
sandboxing
• SD card is less protected
Untrusted Sources
• Inputs from SD card, Internet, Wi-Fi,
Bluetooth, etc.
• Verify authenticity with signature, encryption,
or some other validation
• Be careful loading classes or running
executables from untrusted locations
• Cryptographic protections are the best
Minimal Permissions
• Request the fewest permissions needed for
your app
• This is safer, and also avoids worrying careful
users
• Avoid risky permissions
• INSTALL_PACKAGES
• Using powerful shared users such as
android.uid.system
Bundling Files in the APK
• APK can contain extra files by accident
• May contain SSH credentials or other
secrets
Essential Security
Mechanisms
Review Entry Points
• Trace these functions
Permission Protection
• Exported components should be limited with
permissions
• Only available to apps with the same
signature
• If you really want to offer a component for
public use
• Great care is required in the implementation
Securing Activities
Task Manager Snooping
• Remove your app from the recent app list
• Put this code in OnCreate() to show a blank
screen in the list
getWindow().addFlags(WindowManager.LayoutParams
.FLAG_SECURE);
• Set this attribute in an activity to remove it
entirely from the list
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_

FROM_RECENTS);
Tapjacking
• Prevent touches from being sent through
elements with this attribute:
android:filterTouchesWhenObscured="true"
• Or by using this method:
view.setFilterTouchesWhenObscured(true);
Dictionary
• Disable additions to the dictionary to keep
passwords and other secrets out
• Add this attribute to an EditText box:
android:imputType="textVisiblePassword"
Fragment Attacks
• Since Android 4.4, fragments are blocked by
default
• Use this code to allow a whitelist of fragments:
@Override
protected boolean isValidFragment(String
fragmentName) {
String[] validFragments =
{"com.myapp.pref.frag1",
"com.myapp.pref.frag2"};
return Arrays.asList(validFragments).

contains(fragmentName);
}
Secure Trust Boundaries
• Make sure there's no way to open an
authenticated activity from unauthenticated
areas of the app
• One way: implement an app-wide
authentication variable
Masking Password Displays
• Add this attribute to an EditText box:
android:imputType="textPassword"
Browsable Activities
• Can be used directly from a web browser
• High-value targets for attackers
• Avoid using BROWSABLE
• If you use it, consider all possible intents that
could cause actions in your app
Securing Content Providers
Default Export Behavior
• Prior to API 17, content providers were
exported by default
• To prevent this, put this code in the manifest:
<provider
android:name=".ContentProvider"

android:authorities="com.myapp.ContentProvider"
android:exported="false" >
</provider>
SQL Injection
• Use prepared statements, like this:
String[] userInput = new String[] {"book",
"wiley"};
Cursor c = database.rawQuery("SELECT * FROM
Products WHERE type=?
AND brand=?", userInput);
Directory Traversal
• The getCanonicalPath() method removes ..
characters and provides the absolute path to a
file
• The code on the next page uses this to limit
paths to the /files/ subdirectory of the app's
private data directory
CNIT 128 9. Writing Secure Android Applications
Pattern Matching
• Link
Ch 9a
Securing Broadcast
Receivers
• Secret codes are
easily
enumerated
using apps on
the Play Store
• Don't trust them
Storing Files Securely
Creating Files and Folders
Securely
• Explicitly set permissions
Encryption
• Use AES for symmetric encryption, avoid ECB
• Use RSA-2048 for asymmetric encryption
• Password hashing advice in textbook is wrong
• You need salting and stretching; better to
avoid doing it yourself
Random Numbers
• Random() produces the same series of
numbers each time it's run from the same seed
• SecureRandom is better
• Java provides methods to seed it from a
source of entropy
Random()
import java.util.Random;
class Main {
public static void main(String[] args) {
// create instance of Random class
Random rand = new Random(1);
// Generate random integers in range 0 to 999
int rand_int1 = rand.nextInt(1000);
int rand_int2 = rand.nextInt(1000);
// Print random integers
System.out.println("Random Integers: "+rand_int1);
System.out.println("Random Integers: "+rand_int2);
}
}
• Link Ch 9b
Key Generation
• PBKDF2 uses many rounds of hashing to
derive a key from a password
• Key should be stored in Android Keystore
Exposing Files
• To allow specified other apps to see a file
• Those apps need com.myapp.docs.READWITE
permission
• They can only access the /document/ folder
Secure Communications
HTTPS
• HTTP is very unsafe
• HTTPS is much better, but depends on trusted
Certificate Authorities (CAs)
• Certificate pinning makes HTTPS even more
secure
• Requiring a specific certificate or CA
Local Communications
• Android API is the best method
• Using network sockets or the clipboard is less
safe
Securing WebViews
WebView
• Lets you display a Web page in an activity
• Often leads to security problems
• If loaded over HTTP, subject to interception
and modification
• Link Ch 9c
• Link Ch 9c
• Link Ch 9c
• Link Ch 9c
Configuring the
Android Manifest
Backups and Debugging
• If android:allowBackup is false, an attacker
can't back up files with physical access to the
device
• android:debuggable allows debugging
• Link Ch 9d
API Version Targeting
• minSdkVersion should be as large as
possible
• Lower values remove new security fixes
• Values below 17 export content providers by
default
Android 9
• Targeting SDK 28+ gives you
• DNS over TLS
• Network TLS by default
• Cleartext traffic must be explicitly set
• Separate WebView directories for each
process
• Can't steal cookies
• Many more changes: link Ch 9e
Logging
• Should be disabled in release builds
• Use a centralized logging class
• So it can be easily disabled
• ProGuard can remove logging code
Native Code
• Notoriously difficult to secure
• Limit its exposure to the outside world
• Enable exploit mitigations
• Use latest NDK version
Exploit Mitigations
• RELRO: Relocation Read-Only
• Prevents GOT rewrites
• RPATH / RUNPATH
• Allows attacker to load modified libraries
from a user-controlled path
• Link Ch 9f
Advanced Security
Mechanisms
Protection Level
Downgrade
• Your app can check to make sure the
protection levels are intact at each entry point
Protecting Non-Exported
Components
• Attacker with root permissions can interact
with them
• You can add a request token to prevent that
• Randomly generated
• Stored in a static variable in memory
• Intents must have this token to run
Slowing Down a Reverse
Engineer
Obfuscation
• ProGuard -- free
but very ineffective
• DexGuard -- paid
version of
ProGuard
• Dash-O is good but
expensive ($3000)
• Others compared
at link Ch 9g
Root Detection
• Search for su
• See if default.prop allows ADB shell to run as
root
• See if adbd is running as root
• Look for packages with names like
• SuperSU or Superuser
Emulator Detection
• Check for emulator build properties
Debugger Detection
• Attacker may have modified your app or the
environment to allow debugging
Tamper Detection
• Check signature
CNIT 128 9. Writing Secure Android Applications

More Related Content

PDF
CNIT 128 2. Analyzing iOS Applications (Part 1)
PDF
CNIT 128 7. Attacking Android Applications (Part 1)
PDF
CNIT 128 2. Analyzing iOS Applications (Part 2)
PDF
CNIT 128 8. Identifying and Exploiting Android Implementation Issues (Part 2)
PDF
CNIT 128 7. Attacking Android Applications (Part 3)
PDF
CNIT 128: 3. Attacking iOS Applications (Part 2)
PDF
CNIT 128 7. Attacking Android Applications (Part 2)
PDF
CNIT 128 8. Identifying and Exploiting Android Implementation Issues (Part 3)
CNIT 128 2. Analyzing iOS Applications (Part 1)
CNIT 128 7. Attacking Android Applications (Part 1)
CNIT 128 2. Analyzing iOS Applications (Part 2)
CNIT 128 8. Identifying and Exploiting Android Implementation Issues (Part 2)
CNIT 128 7. Attacking Android Applications (Part 3)
CNIT 128: 3. Attacking iOS Applications (Part 2)
CNIT 128 7. Attacking Android Applications (Part 2)
CNIT 128 8. Identifying and Exploiting Android Implementation Issues (Part 3)

What's hot (20)

PDF
CNIT 128 7. Attacking Android Applications (Part 3)
PDF
CNIT 128 6. Analyzing Android Applications (Part 1)
PDF
CNIT 128 9. Writing Secure Android Applications
PDF
CNIT 128: Android Implementation Issues (Part 2)
PDF
CNIT 128 6. Analyzing Android Applications (Part 3 of 3)
PDF
CNIT 128 8. Identifying and Exploiting Android Implementation Issues (Part 1)
PDF
CNIT 128 3. Attacking iOS Applications (Part 1)
PDF
CNIT 128 6. Analyzing Android Applications (Part 3)
PDF
CNIT 128 7. Attacking Android Applications (Part 2)
PDF
CNIT 128 6. Analyzing Android Applications (Part 2 of 3)
PDF
CNIT 129S: Ch 12: Attacking Users: Cross-Site Scripting
PDF
CNIT 128 8. Android Implementation Issues (Part 3)
PDF
CNIT 141: 13. TLS
PDF
CNIT 128: 7. Attacking Android Applications (Part 1 of 3)
PDF
CNIT 128 8. Android Implementation Issues (Part 2)
PPT
iOS Application Pentesting
PDF
Anti-tampering in Android and Take Look at Google SafetyNet Attestation API
PDF
CNIT 128 3. Attacking iOS Applications (Part 2)
PDF
Shellcoding in linux
PDF
CNIT 126: Ch 2 & 3
CNIT 128 7. Attacking Android Applications (Part 3)
CNIT 128 6. Analyzing Android Applications (Part 1)
CNIT 128 9. Writing Secure Android Applications
CNIT 128: Android Implementation Issues (Part 2)
CNIT 128 6. Analyzing Android Applications (Part 3 of 3)
CNIT 128 8. Identifying and Exploiting Android Implementation Issues (Part 1)
CNIT 128 3. Attacking iOS Applications (Part 1)
CNIT 128 6. Analyzing Android Applications (Part 3)
CNIT 128 7. Attacking Android Applications (Part 2)
CNIT 128 6. Analyzing Android Applications (Part 2 of 3)
CNIT 129S: Ch 12: Attacking Users: Cross-Site Scripting
CNIT 128 8. Android Implementation Issues (Part 3)
CNIT 141: 13. TLS
CNIT 128: 7. Attacking Android Applications (Part 1 of 3)
CNIT 128 8. Android Implementation Issues (Part 2)
iOS Application Pentesting
Anti-tampering in Android and Take Look at Google SafetyNet Attestation API
CNIT 128 3. Attacking iOS Applications (Part 2)
Shellcoding in linux
CNIT 126: Ch 2 & 3
Ad

Similar to CNIT 128 9. Writing Secure Android Applications (20)

PDF
9 Writing Secure Android Applications
PDF
Mitigating Java Deserialization attacks from within the JVM
PDF
Mitigating Java Deserialization attacks from within the JVM (improved version)
PDF
cf.Objective() 2017 - Design patterns - Brad Wood
ODP
CISSP Week 14
PDF
Unsafe Deserialization Attacks In Java and A New Approach To Protect The JVM ...
PPTX
Secure Coding 101 - OWASP University of Ottawa Workshop
PDF
Higher Level Malware
PDF
Yow connected developing secure i os applications
PPTX
Cm9 secure code_training_1day_input sanitization
PDF
RIoT (Raiding Internet of Things) by Jacob Holcomb
PDF
Breaking Secure Mobile Applications - Hack In The Box 2014 KL
PDF
Metasploit Computer security testing tool
PPT
Dominique
PDF
iOS Application Security.pdf
PPTX
From java to android a security analysis
PPTX
Kubernetes and container security
PDF
Coding for production
9 Writing Secure Android Applications
Mitigating Java Deserialization attacks from within the JVM
Mitigating Java Deserialization attacks from within the JVM (improved version)
cf.Objective() 2017 - Design patterns - Brad Wood
CISSP Week 14
Unsafe Deserialization Attacks In Java and A New Approach To Protect The JVM ...
Secure Coding 101 - OWASP University of Ottawa Workshop
Higher Level Malware
Yow connected developing secure i os applications
Cm9 secure code_training_1day_input sanitization
RIoT (Raiding Internet of Things) by Jacob Holcomb
Breaking Secure Mobile Applications - Hack In The Box 2014 KL
Metasploit Computer security testing tool
Dominique
iOS Application Security.pdf
From java to android a security analysis
Kubernetes and container security
Coding for production
Ad

More from Sam Bowne (20)

PDF
Introduction to the Class & CISSP Certification
PDF
Cyberwar
PDF
3: DNS vulnerabilities
PDF
8. Software Development Security
PDF
4 Mapping the Application
PDF
3. Attacking iOS Applications (Part 2)
PDF
12 Elliptic Curves
PDF
11. Diffie-Hellman
PDF
2a Analyzing iOS Apps Part 1
PDF
12 Investigating Windows Systems (Part 2 of 3)
PDF
10 RSA
PDF
12 Investigating Windows Systems (Part 1 of 3
PDF
9. Hard Problems
PDF
8 Android Implementation Issues (Part 1)
PDF
11 Analysis Methodology
PDF
8. Authenticated Encryption
PDF
7. Attacking Android Applications (Part 2)
PDF
7. Attacking Android Applications (Part 1)
PDF
5. Stream Ciphers
PDF
6 Scope & 7 Live Data Collection
Introduction to the Class & CISSP Certification
Cyberwar
3: DNS vulnerabilities
8. Software Development Security
4 Mapping the Application
3. Attacking iOS Applications (Part 2)
12 Elliptic Curves
11. Diffie-Hellman
2a Analyzing iOS Apps Part 1
12 Investigating Windows Systems (Part 2 of 3)
10 RSA
12 Investigating Windows Systems (Part 1 of 3
9. Hard Problems
8 Android Implementation Issues (Part 1)
11 Analysis Methodology
8. Authenticated Encryption
7. Attacking Android Applications (Part 2)
7. Attacking Android Applications (Part 1)
5. Stream Ciphers
6 Scope & 7 Live Data Collection

Recently uploaded (20)

PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
master seminar digital applications in india
PPTX
Pharma ospi slides which help in ospi learning
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
Presentation on HIE in infants and its manifestations
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Structure & Organelles in detailed.
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
O7-L3 Supply Chain Operations - ICLT Program
Pharmacology of Heart Failure /Pharmacotherapy of CHF
master seminar digital applications in india
Pharma ospi slides which help in ospi learning
Supply Chain Operations Speaking Notes -ICLT Program
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Chinmaya Tiranga quiz Grand Finale.pdf
Presentation on HIE in infants and its manifestations
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Anesthesia in Laparoscopic Surgery in India
Cell Structure & Organelles in detailed.
VCE English Exam - Section C Student Revision Booklet
Final Presentation General Medicine 03-08-2024.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf

CNIT 128 9. Writing Secure Android Applications

  • 1. CNIT 128 Hacking Mobile Devices 9. Writing Secure 
 Android Apps
  • 2. Common Vulnerabilities • Code injection • Logic flaws • Insecure storage • Application configuration • Insecure communication • Logging
  • 3. Topics • Principle of Least Exposure • Essential Security Mechanisms • Advanced Security Mechanisms • Slowing Down a Reverse Engineer
  • 5. Minimizing Attack Surface • Find all entry points • Code exposed to inputs from outside sources • Remove unnecessary entry points • Perform security checks at necessary entry points
  • 6. App Components • Don't export more components than required • The safest case is shown below • Most apps require some integration with other apps
  • 7. Data Storage • Avoid storing unnecessary data • Such as passwords! • Private directory is protected somewhat by the sandboxing • SD card is less protected
  • 8. Untrusted Sources • Inputs from SD card, Internet, Wi-Fi, Bluetooth, etc. • Verify authenticity with signature, encryption, or some other validation • Be careful loading classes or running executables from untrusted locations • Cryptographic protections are the best
  • 9. Minimal Permissions • Request the fewest permissions needed for your app • This is safer, and also avoids worrying careful users • Avoid risky permissions • INSTALL_PACKAGES • Using powerful shared users such as android.uid.system
  • 10. Bundling Files in the APK • APK can contain extra files by accident • May contain SSH credentials or other secrets
  • 12. Review Entry Points • Trace these functions
  • 13. Permission Protection • Exported components should be limited with permissions • Only available to apps with the same signature • If you really want to offer a component for public use • Great care is required in the implementation
  • 15. Task Manager Snooping • Remove your app from the recent app list • Put this code in OnCreate() to show a blank screen in the list getWindow().addFlags(WindowManager.LayoutParams .FLAG_SECURE); • Set this attribute in an activity to remove it entirely from the list intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_
 FROM_RECENTS);
  • 16. Tapjacking • Prevent touches from being sent through elements with this attribute: android:filterTouchesWhenObscured="true" • Or by using this method: view.setFilterTouchesWhenObscured(true);
  • 17. Dictionary • Disable additions to the dictionary to keep passwords and other secrets out • Add this attribute to an EditText box: android:imputType="textVisiblePassword"
  • 18. Fragment Attacks • Since Android 4.4, fragments are blocked by default • Use this code to allow a whitelist of fragments: @Override protected boolean isValidFragment(String fragmentName) { String[] validFragments = {"com.myapp.pref.frag1", "com.myapp.pref.frag2"}; return Arrays.asList(validFragments).
 contains(fragmentName); }
  • 19. Secure Trust Boundaries • Make sure there's no way to open an authenticated activity from unauthenticated areas of the app • One way: implement an app-wide authentication variable
  • 20. Masking Password Displays • Add this attribute to an EditText box: android:imputType="textPassword"
  • 21. Browsable Activities • Can be used directly from a web browser • High-value targets for attackers • Avoid using BROWSABLE • If you use it, consider all possible intents that could cause actions in your app
  • 23. Default Export Behavior • Prior to API 17, content providers were exported by default • To prevent this, put this code in the manifest: <provider android:name=".ContentProvider"
 android:authorities="com.myapp.ContentProvider" android:exported="false" > </provider>
  • 24. SQL Injection • Use prepared statements, like this: String[] userInput = new String[] {"book", "wiley"}; Cursor c = database.rawQuery("SELECT * FROM Products WHERE type=? AND brand=?", userInput);
  • 25. Directory Traversal • The getCanonicalPath() method removes .. characters and provides the absolute path to a file • The code on the next page uses this to limit paths to the /files/ subdirectory of the app's private data directory
  • 28. Securing Broadcast Receivers • Secret codes are easily enumerated using apps on the Play Store • Don't trust them
  • 30. Creating Files and Folders Securely • Explicitly set permissions
  • 31. Encryption • Use AES for symmetric encryption, avoid ECB • Use RSA-2048 for asymmetric encryption • Password hashing advice in textbook is wrong • You need salting and stretching; better to avoid doing it yourself
  • 32. Random Numbers • Random() produces the same series of numbers each time it's run from the same seed • SecureRandom is better • Java provides methods to seed it from a source of entropy
  • 33. Random() import java.util.Random; class Main { public static void main(String[] args) { // create instance of Random class Random rand = new Random(1); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println("Random Integers: "+rand_int1); System.out.println("Random Integers: "+rand_int2); } }
  • 35. Key Generation • PBKDF2 uses many rounds of hashing to derive a key from a password • Key should be stored in Android Keystore
  • 36. Exposing Files • To allow specified other apps to see a file • Those apps need com.myapp.docs.READWITE permission • They can only access the /document/ folder
  • 38. HTTPS • HTTP is very unsafe • HTTPS is much better, but depends on trusted Certificate Authorities (CAs) • Certificate pinning makes HTTPS even more secure • Requiring a specific certificate or CA
  • 39. Local Communications • Android API is the best method • Using network sockets or the clipboard is less safe
  • 41. WebView • Lets you display a Web page in an activity • Often leads to security problems • If loaded over HTTP, subject to interception and modification
  • 47. Backups and Debugging • If android:allowBackup is false, an attacker can't back up files with physical access to the device • android:debuggable allows debugging • Link Ch 9d
  • 48. API Version Targeting • minSdkVersion should be as large as possible • Lower values remove new security fixes • Values below 17 export content providers by default
  • 49. Android 9 • Targeting SDK 28+ gives you • DNS over TLS • Network TLS by default • Cleartext traffic must be explicitly set • Separate WebView directories for each process • Can't steal cookies • Many more changes: link Ch 9e
  • 50. Logging • Should be disabled in release builds • Use a centralized logging class • So it can be easily disabled • ProGuard can remove logging code
  • 51. Native Code • Notoriously difficult to secure • Limit its exposure to the outside world • Enable exploit mitigations • Use latest NDK version
  • 52. Exploit Mitigations • RELRO: Relocation Read-Only • Prevents GOT rewrites • RPATH / RUNPATH • Allows attacker to load modified libraries from a user-controlled path • Link Ch 9f
  • 54. Protection Level Downgrade • Your app can check to make sure the protection levels are intact at each entry point
  • 55. Protecting Non-Exported Components • Attacker with root permissions can interact with them • You can add a request token to prevent that • Randomly generated • Stored in a static variable in memory • Intents must have this token to run
  • 56. Slowing Down a Reverse Engineer
  • 57. Obfuscation • ProGuard -- free but very ineffective • DexGuard -- paid version of ProGuard • Dash-O is good but expensive ($3000) • Others compared at link Ch 9g
  • 58. Root Detection • Search for su • See if default.prop allows ADB shell to run as root • See if adbd is running as root • Look for packages with names like • SuperSU or Superuser
  • 59. Emulator Detection • Check for emulator build properties
  • 60. Debugger Detection • Attacker may have modified your app or the environment to allow debugging