3. Attack Vector
Definition: Attack Vector is a method malicious code uses
to propagate itself or infect a computer
● Example 1: sending an MMS with attached video that triggers StageFright
multimedia framework buffer overflow when processing video metadata
● Example 2: triggering adb sessions in loop until max_pid limit is reached
for user, thus obtaining a root shell, as adbd does not check setuid ret
● Example 3: WebKit javascript parseFloat bug which can trigger malicious
code, even get root shell when browsing to a web page
4. Attack Surface
Definition: Sum of attack vectors in a software environment
where attacker can try to enter data or extract data from a
computer
● Example 1: WebKit, exposed both to apps and to outside world (servers)
● Example 2: Baseband, exposed to apps via telephony framework, and
outside world via MMS, SMS and phone calls
● Example 3: StageFright, exposed to local apps, to MMS attacks
(processing of metadata when building MMS notification), outside servers
5. Mobile Attack Surface: the device
● Browser: phishing, Framing, clickjacking, man in the middle, buffer
overflow, data caching
● System: passcode, rooting, OS data caching, keystore, bloatware,
encryption
● Phone/SMS/MMS: baseband attacks, SMishing, MMSishing
● Apps: sensitive data storage, encryption, SSL validation, config
manipulation, dynamic runtime inspection, unintended permissions,
escalated privileges
● INSTALLED MALWARE!!!
6. External Attack Surfaces
● The Network: Wi-Fi encryption, rogue access point, sniffing, Man in the
Middle, session hacking, DNS poisoning, SSL strip, fake SSL certificate
● Web Server: platform vulnerabilities, misconfiguration, XSS (cross site
scripting), CSRF/XSRF (Cross site request forgery), weak input validation,
brute force attacks
● Database: SQL injection, privilege escalation, data dumping, OS command
execution
7. Browser based attacks
● Phising - acquiring personal data by masquerading as trusted entity
● Framing - delivering a Web/WAP site in an iFrame, which can enable clickjacking
● Clickjacking - taking control of users device or forcing him to reveal confidential
information when a user clicks a link or a button via embedded code
● Drive-by downloading - web site causes download without users knowledge
● Main in the mobile (MitMo) - malware circumventing identity verification
systems using SMS
8. Phone/SMS based attacks
● Baseband attacks - exploit vulnerabilities in GSM/3gpp baseband processor
● SMSiShing - similar to phishing, uses SMS/MMS to prompt users to visit
illegitimate sites
● RF Attacks (Bluejacking, NFC, and other exploits) - using vulnerabilities in various
peripheral communication channels that are typically used in nearby device-to-
device communication
9. Application based attacks
● Sensitive data storage - 83% of popular apps store data insecurely
● Encryption - apps allow transfer of weakly encrypted or unencrypted sensitive data
● Improper SSL validation - bugs in SSL validation may allow data breaches
● Config manipulation - gaining unauthorized access to administration interfaces
● Dynamic runtime injection - manipulation and abuse of application runtime to
bypass security locks
● Unintended permissions - misconfigured apps can open door to attacker by
granting unintended permissions
● Escalated privilege - uses a bug to gain access to resources protected from app or
user
10. OS based attacks
● No passcode - users do not set, or set a weak passcode or pin
● Rooting - allow users to alter or replace applications or settings by
acquiring privileged account access
● Passwords and data accessible - exploiting vulnerabilities in crypto
mechanisms and keystores to get passwords and certificates
● Bloatware - pre-installed software can contain security flaws
● Zero-day exploits - attacks occur between the day vulnerability is
discovered and patch is released
11. Network based attacks
● Wi-Fi - apps failing to implement encryption when used on public Wi-Fi run risk of
being intercepted, when connected to LAN, you not protected by firewall
● Rogue access points - installing unauthorized wireless access point
● Packet sniffing - intruder captures and analyzes network traffic
● Man in the middle (MITM) - sniffing, intercepting and modifying sent
data/responses
● SLStrip - MITM that exploits weaness in SSL/TLS on web sites
● Session hijacking - exploitation of a session key to gain unauthorized access
● DNS poisoning - DNS can be used to direct users to a fake server
● Fake SSL certs - MITM that involves issuing fake SSL certs that allow interception
12. Server based attacks
● Platform vulnerabilities - vulnerabilities on server OS, software or app modules
● Misconfiguration - poorly configured server may allow unauthorized access
● Cross-site scripting (XSS) - attack that involves injecting JS into a website
● Cross-site Request Forgery (CSRF) - tricking a browser in executing requests, used
when attacker gained control of user's session via XSS, social engineering, etc
● Weak input validation - servers trust apps to validate user submitted data, hacker
can forge communications, or exploit the app into unintended behavior
● Brute force attacks - guessing valid inputs, often using dictionaries, most common
usage is password guessing
13. Database attacks
● QL injection - when user input is not validated, it can cause to modify SQL
query being made
● OS command execution - similar to injection, some databases can provide
means of executing OS-level commands
● Privilege escalation - attacker leverages some exploit to gain greater
access, thus exposing/stealing sensitive data
● Data dumping - attacker causes database to dump some or all data within
the database, exposing sensitive records
14. Notable Hacking Techniques
● Brute force/dictionary attacks - attacker uses a dictionary to try to guess user
inputs, usually passwords
● Fuzzing - attacker scripts random calls to exposed interfaces to the app, marking
results, crash or freeze often indicates an exploitable interface
● Heap spraying - filling heap with malicious executable code in hope that badly
written code will pick it up and execute it
● Stack overflowing - writing too much data to a stack array, thus overwriting
variables and return addresses on the application stack
● Return oriented programming (ROP) - technique where attacker maps snippets of
executable code in memory (gadgets), builds a chain of them to execute an attack
15. Notable Anti-Hacking Features
● XN (execute never, or NX) - feature in processors that mark memory as executable
or not executable, if it is not executable and instruction pointer points to it, it will
cause access violation exception, and kernel will terminate program (prevents
execution of code in data memory, forces hackers to do ROP)
● Stack cookies - random integer added to start and end of stack entry, upon exiting
code block (stack pop), values are compared (anti stack overflowing)
● ASLR (address randomization) - libraries are loaded in random addresses (gadgets
need to be re-found every time app runs)
● RELRO - executable data sections are reordered, so that process data precedes user
data (stack overflowing is harder)
● Bind now - lib symbols are lazy resolved, loaded only when used (less gadgets)
16. Code complexity and obfuscation
● Increasing code complexity makes it harder to understand how application operates
when reverse engineering
● Obfuscation hides method and variable names, thus hiding their real purpose
● Restricting debuggers prevents hacker from examining the running app’s flow and
stack, using ptrace(PT_DENY_ATTACH, …) system call
● Trace checking - app can check weather a debugger is attached via /proc/self
● Optimizations hide mathematical computations and other types of complex logic
● Stripping native binaries increases time and skill required to reverse your app,
compile without debug data, disable stack unwinding, if possible disable C++
exceptions to prevent fuzzing from revealing too much
18. Avoid simple logics
Using simple logic makes your application more susceptible to attack. Code
such as this introduces a single point of failure:
if(sessionIsTrusted) { …
Consider a better programming paradigm, where privileges are enforced by
server, encrypting sensitive data, or determining if session is trusted by
challenge/response, OTP, or other form of authentication
19. Test Third-Party Libraries
Third-Party libraries need to be security-audited to the same level as application
code. Upgrading a library or OS version should be treated as upgrade of version of
your app.
Do not fully trust even the on-device framework, as it can be modified by an attacker.
Example: when using ART, Android devices compile framework dex files to OAT files
when ever framework is upgraded and saved in /data/dalvik-cache directory which is
writable. Compiler, dex2oat exists on the device, and attacker can re-compile the
framework where he supplies his malicious version of the code. See “Hiding behind
ART 2015 BlackHat talk.
20. Implement anti-tamper techniques
Attackers can tamper with an app, re-sign it and publish it to marketplaces.
Use checksums, signatures, and other validation mechanisms, and validate
them against a server before assuming secure environment.
Example: when validating session with the server, include application signature
in the protocol, which can be checked against database of released versions.
Similar check can be implemented locally
21. Securely Store Sensitive Data in RAM
Android applications store data in RAM even after use, until memory is
reclaimed.
Do not keep sensitive data such as encryption keys and passwords in RAM
longer than necessary. Avoid using immutable objects for them such as
java.lang.String, and use char array instead. If possible, overwrite the
data when you are done with it.
22. Understand Secure Deletion of Data
Deleting a file only detaches its pointer, data is not overwritten, and can be
recovered. Overwriting the data is not recommended as it wears out NAND
flash.
Whenever possible, avoid storing sensitive data on device. If it is not possible,
store it encrypted.
23. Avoid Query Strings for Sensitive Data
HTTP GET query parameters are visible and can be cached.
Use HTTP POST with XSRF token protection. Weather using POST or GET,
temporary session cookies should be used. Encrypting data using a non-zero
initialization vector and temporary session keys can also help.
24. Implement Secure Data Storage
Storing data securely on a mobile device requires proper techniques.
Whenever possible, do not store/cache data. Transmit and display, but do not
persist in memory or storage. When done with sensitive data, zero the memory
where it was stored. If storing data is unavoidable, add a layer of verified third
party encryption. Be careful with built in encryption, for example, AES defaults
to less secure AES-ECB, it is better to specify AES-CBC or AES-GCM with 256
bit key. Also, framework could be compromised.
25. Use SECURE Setting For Cookies
Cookie not marked as secure may be transmitted over an insecure connection.
Set-Cookie headers should use “Secure” and “HTTPOnly” settings.
26. Fully Validate SSL/TLS
Many apps do not implement proper validation of certificates. Make sure to
properly implement X509TrustManager checkClientTrusted and
checkServerTrusted. Do not setHostVerifier to
SSLSocektFactory.ALLOW_ALL_HOSTNAME_VERIFIER
27. Fully Validate SSL/TLS: good practice
InputStream in = resources.openRawResource(certificateRawResource);
keyStore = KeyStore.getInstance("BKS");
keyStore.load(resourceStream, password);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 443));
ThreadSafeClientConnManager clientMan =
new ThreadSafeClientConnManager(httpParams, schemeRegistry);
httpClient = new DefaultHttpClient(clientMan, httpParams);
28. Protect Against SSL Downgrade
Form of MITM, attacker bypases SSL/TLS by hijacking HTTP traffic, monitoring
for HTTPS requests and eliminating SSL/TLS.
Serve all traffic on TLS, even non-sensitive. Attacker needs an entry point to
accomplish his attack. Validate that TLS is active. From Marshmellow, new
application attribute was added to manifest. Make sure it is defined:
android:usesCleartextTraffic=”false”
29. Limit Use of UUID
Using UUID, IMEI or similar for user identification is a privacy concern, and after
resetting the phone, next user will gain access to previous user’s data.
Recommended is to create app-unique device factor at time of registration,
installation or first execution.
30. Treat Geolocation Data Carefully
Mishandling GPS data is a privacy concern, as it may reveal user’s present and
past locations. Apps with access to gallery can access geolocation data from
EXIF tags of pictures.
Unless required, do not access or store location data, and if possible use more
coarse data. When working in secure locations, remember that GPS data may
be reported by various applications to their servers. Do not activate GPS in
applications that will run in secure locations.
31. Institute local session timeout
Mobile devices are frequently lost or stolen, attacker can use active session to
access sensitive data, execute transactions, or perform reconnaissance on
device owner’s accounts.
When app is not used for 5 minutes, terminate the session and redirect user to
login screen, ensure that no app data is visible, and require the user to re-enter
login or credentials to access the app. Also, after timeout, clear all memory
associated with user data, including master keys used to decrypt. And make
sure that timeout occurs on both server and client.
32. Implement Enhanced / Two-Factor
Authentication
Weak or non-existent authentication can grant an attacker unauthorized access
to an app.
A password should not be simplistic. It’s best to require, if not at least support,
complex passwords, including length of at least six alphanumeric characters
(more characters is always stronger). Requiring the selection of a secret word
or icon (which the user does not create themselves) as part of the log-in
process can help protect users' accounts in the event they re-use passwords
and their password was exposed as part of another data compromise.
33. Protect Application Settings
Developers often store settings in a shared preferences XML file or SQLite
databases, which are not encrypted by default and can be read or even
modified with root permissions, or using backup procedures.
Compile settings into the code when possible. Configuration inside app code
which requires more time and skill for attackers to modify. Don’t store any
critical settings in dictionaries or other files unless encrypted first. Ideally,
encrypt all configuration files using a master key encrypted with a passphrase
that is supplied by the user, or with a key provided remotely when a user logs
into a system.
34. Hide Account Numbers and Use Tokens
Many apps store complete account numbers in various screens.
Given the widespread use of mobile apps in public places, displaying partial
numbers (e.g. *9881) can help ensure maximum privacy for this information.
Unless there is a need to store the complete number on the device, store the
partially hidden numbers.
35. Implement Secure Network Transmission Of
Sensitive Data
Unlike web browsers, mobile devices typically do not disclose whether or not
an app uses SSL/TLS to secure the transmission of data, and so app users
simply have to trust that the app’s developer has implemented network
encryption.
Use SSL/TLS either with standard trust validation, or, for increased security,
implement certificate pinning (see also best practice “Fully Validate SSL/TLS”
and the OWASP “Pinning Cheat Sheet”). To prevent leak via compromised
SSL/TLS connection, encrypt super sensitive data like logins, passwords, CC
numbers, with AES with key with length of 256.
36. Validate Input From Client
Even if data is is generated from your app, it is possible for this data to have
been intercepted and manipulated. This could include attacks that cause the
app to crash (generating a key crash log), buffer overflows, SQL Injection, and
other attacks.
As with proper web application security, all input from the client should be must
be treated as untrusted. Services must thoroughly filter and validate input from
the app and user. Proper sanitization includes all user input before transmitting
and during receipt.
37. Avoid Storing App Data in Backups
Performing a backup of the data on an Android or iOS device can potentially
also back-up sensitive information stored within an app’s private directory.
By default, the allowBackup flag within an Android app’s Manifest file is set as
true. This results in an Android backup file (backup.ab) including all of
subdirectories and files contained within an app’s private directory on the
device’s file system. Therefore, explicitly declare the allowBackup flag as false.
38. Avoid Caching App Data
Data can be captured in a variety of artifacts – many unintended. Developers
often overlook some of the ways data can be stored including log/debug files,
cookies, web history, web cache, property lists, files and SQLite databases.
Storing data securely on a mobile device requires proper technique. Whenever
possible, simply do not store/cache data. This is the most sure way to avoid
data compromise on the device.
Prevent HTTP caching. Developers can configure Android to not cache web
data, particularly HTTPS traffic. In addition, we recommend that steps be taken
to avoid caching of URL history and page data for any Web process such as
39. Avoid Crash Logs
There are several frameworks for tracking user usage and collect crash logs for
iOS and Android, both are useful tools for development, but it is important to
find a balance between enough debug information for the developers and
reduced information for attackers.
Ensure released apps are built without warnings and are thoroughly tested to
avoid crashes. This is certainly always the goal and worth mentioning due to
the value of a crash log. In addition, if the app is obfuscated and stripped, the
developer will need keep an address-to-symbol database in order to recover
meaningful backtraces in crashlogs, making attacker's life harder because of
the lack of understandable names in functions.
40. Carefully Manage Debug Logs
Debug logs are generally designed to be used to detect and correct flaws in an
application. These logs can leak sensitive information that may help an
attacker create a more powerful attack.
Developers should consider the risk that debug logs may pose in a production
setting. Generally we recommend that they are disabled in production. It is
mode secured if logging calls are stripped in obfuscation/minifying process
rather than using a variable that is evaluated in runtime.
SET THE “ANDROID:DEBUGGABLE” FLAG TO “FALSE” IN PRODUCTION BUILDS!
41. Be Aware of the Keyboard Cache
Keyboard logs what users type in order to provide features such as customized
auto-correct and form completion, but sensitive data may also be stored.
Android contains a user dictionary, where words entered by a user can be
saved for future auto-correction. This user dictionary is available to any app
without special permissions. For increased security, consider implementing a
custom keyboard (and potentially PIN entry), which can disable caching and
provide additional protection against malware.
42. Be Aware of Copy and Paste
Sensitive data may be stored, recoverable, or could be modified from the
clipboard in clear text, regardless of whether the source of the data was initially
encrypted.
Where appropriate, disable copy/paste for areas handling sensitive data.
Eliminating the option to copy can help avoid data exposure. On Android the
clipboard can be accessed by any application and so it is recommended that
appropriately configured Content Providers be used to transfer complex
sensitive data.
43. Prevent Framing and Clickjacking in
Webviews
Framing involves delivery of a Web/WAP site within an iFrame. This attack can
enable the “wrapper” site to execute a clickjacking attack. Clickjacking is a very
real threat that has been exploited on high-profile services (e.g., Facebook) to
steal information or redirect users to attacker controlled sites.
The best way to prevent this practice is to not use WebViews.
44. Protect Against CSRF with Form Tokens
CSRF (Cross-site Request Forgery) relies on known or predictable form values
and a logged-in browser session.
Each form submission should contain a token which was loaded with the form
or at the beginning of a user session. Check this token on the server when
receiving POST requests to ensure the user originated it. This capability is
provided with major web platforms and can be implemented on forms with
minimal custom development.
45. Implement File Permissions Carefully
World readable files can act as a vector for your program to leak sensitive
information. World writeable files may expose your app by letting an attacker
influence its behavior by overwriting data that is read by your app from storage.
Examples include settings files and stored login information.
Do not create files with permissions of MODEWORLD_READABLE or
MODE_WORLD_WRITABLE if possible. Do not use modes such as 0666, 0777,
and 0664 with the chmod binary or syscalls.
46. Check Activities
An Activity can be invoked by any application if it is exported and enabled. This
could allow an attacker to load UI elements in a way the developer may not
intend, such as jumping past a password lock screen to access data or
functionality. By default Activities are not exported, however, if you define an
Intent filter for an Activity it will be exported by the system.
Have all components that do not have to be exposed set to
android:exported=false in Manifest. Data received by public components
cannot be trusted and must be scrutinized. Avoid intent filters on Activities if
they are private, instead use explicit intent.
47. Use Broadcasts Carefully
If no permission is set when sending a broadcast Intent, then any unprivileged
app can receive the Intent unless it has an explicit destination.
Use permissions to protect Intents in your application. Keep in mind that when
sending information via a broadcast Intent to a third party component, that
component could have been replaced by a malicious install.
48. Protect Application Services
Services are typically used for background processing. Like BroadcastReceivers
and application activities, application services can be invoked by external
applications and so should be protected by permissions and export flags.
A service may have more than one method which can be invoked from an
external caller. It is possible to define arbitrary permissions for each method
and check if the calling package has the corresponding permission by using
checkPermission(). Alternatively, one could define separate services and secure
access through the use of permissions defined in the AndroidManifest.
49. Avoid Intent Sniffing
When an activity is initiated by another application using a broadcast intent, the
data passed in the intent can be read by a malicious app.
When another application initiates activity by sending a broadcast intent,
malicious apps can read the data included in the intent. The malicious app can
also read a list of recent intents for an application. For example, if an app
invokes and passes a URL to the Android web browser, an attacker could sniff
that URL.
50. Implement Content Providers Carefully
Content providers allow apps to share data using a URI-addressing scheme and
relational database model. They can also be used to access files via the URI
scheme.
Content providers can declare permissions and separate read and write
access. Do not give a content provider write access unless it's absolutely
necessary. Make sure to set permissions so that unprivileged apps cannot read
the ContentProvider instance unless required. Do sanitation of SQL queries, file
paths, etc, you get from outside. Limit access to minimum required for
operation.
51. Follow WebView Best Practices (if you must)
WebViews can introduce a number of security concerns and should be
implemented carefully. In particular, a number of exploitable vulnerabilities
arising from the use of the addJavscriptInterface API have been discovered.
Disable JavaScript and Plugin support if they are not needed. Disallow the
loading of content from third-party hosts. This can be difficult to achieve from
within the app. However, a developer can override shouldOverrideUrlLoading
and shouldInterceptRequest to intercept, inspect, and validate most requests
initiated from within a WebView. See GIST for a snippet of code that includes
some WebView security best practices.
52. Avoid Storing Cached Camera Images
Remote-check-deposit apps allow a person to take a picture of a check with
their mobile phone's camera and then send the image to their financial
institution for deposit into their account.
Many of these apps will retain the check image (or part of it) in the mobile
device's NAND memory even after it is deleted. Do not transmit a check image
using non-volatile storage on the device where check image artifacts may be
left behind. Use Camera.PictureCallback.onPictureTaken(byte[] bytes, Camera
camera)
53. Avoid GUI Objects Caching
Android retains application screens in memory, and multitasking can result in
the retention of an entire application in memory. This allows an attacker that
finds or steals a device to navigate directly to retained screens.
Quit the app entirely when the user logs out. Any time an activity is initiated or a
screen is accessed, execute a check to determine whether the user is in a
logged-in state. If the user is not logged in, present the log-in screen. Nullify the
data on a GUI screen before leaving the screen or logging out.
54. Sign Android APKs
APKs should be signed correctly with a non-expired certificate.
Sign a production app with a production certificate, not a debug certificate.
Make sure the certificate includes a sufficient validity period (i.e., won't expire
during the expected lifespan of the app). Google recommends that your
certificate use at least 2048-bit encryption. Make sure the keystore containing
the signing key is properly protected. Restrict access to the keystore to only
those people that absolutely require it.