According to a report by Kapersky Labs, there were 40 million attacks by malicious malware on mobile devices in 2016.
So how to protect your mobile app from that onslaught of attacks? Where to start? If you haven’t invested a lot of time researching mobile security, this article is for you. It examines the different technical and social areas to make your app more secure and shines a light on vulnerabilities and measures to protect your app goodies from the bad guys.
Let’s start with an topic of mobile security measures that is often overlooked: User Education.
1. User Education
User Policies for limiting private use on enterprise devices
if you have a set of employees using apps on an enterprise device, you may want to issue a policy that limits enterprise mobile devices from private use in order to limit certain types of cyber attacks (e.g. phishing, malware installation) and prevent security breaches.
Enforce Mobile Device Management Security (MDM) Policies
Another security measure to protect employees from using private or company mobile devices in a reckless manner is to enforce security policies using a Mobile Device Management system.
MDMs can enforce a variety of policies, such as:
• Device encryption
• Password protection
• Password rules
• Jailbreak check
• Preventing devices to run with unsafe OS versions
• Whitelisting/blacklisting apps to load on the device
User Education about the risks of web surfing
Phishing is a way of attempting to acquire information (and sometimes, indirectly, money) such as usernames, passwords, and credit card details by masquerading as a trustworthy entity in an electronic communication.
Web browsing to malicious web sites may lead to phishing attacks. Users should be educated about the risks
User Education about using screen locks
Mobile devices which are left unlocked and unattended represent a security risk since an unauthorized user may gain access to sensitive or confidential information on the device. To prevent this, the user should be educated to use a screen lock and to lock the device every time after using it.
User education about jailbreaking/rooting
Jailbreaking/Rooting is the action of disabling or overriding the OS security framework in order to perform actions that are not allowed by the OS. This can lead to making the device unusable and to circumvent OS security measures which expose the device to malware attacks and other types of misuse (e.g. OS and DRM licensing violations). Users should be made aware of the risks.
User education about the Mobile Frameword Permission System
iOS and Android operating system rely on the user to provide applications with certain permissions (e.g. GPS, notifications, hardware access) at install or run time. Some permissions – if exploited – may be more harmful than others. The user should understand the risks associated with allowing more harmful permissions.
For example, providing an application with the permission to send SMS messages may expose the device to ‘SMS Trojan’ malwares which deliberately sends SMS to paid SMS service numbers in order to make a profit.
Before users accept mobile app permissions, they should be made aware of the risks associated with the permission.
User education about allowing app installation from unsecure sources
Some operating systems such as Android make it easy to install applications from unsecure distribution channels for example:
– Email attachments
– From a PC using Android debug bridge
– From SD card
Applications installed from unsecure channels may lead to the installation of malware on the device and should be avoided by the user. More secure channels are the MDM enterprise app store and the OS Provider App Stores (Apple App Store, Google Market Place).
User education about storing sensitive data on extenral storage
On some mobile platforms such as Android, the external storage is not encrypted even if the device settings are set to encrypt the device’s internal storage. As a security measure the user should be educated not to store any sensitive information on the external storage (e.g. SD card). Also, SD cards can be easily stolen without the user noticing which makes this security measure more relevant.
User education about using public WiFi hotspots
Users of using a secure app should be informed of the risks of using public WiFi hotspots. There are two main types of risks:
First, public WiFi hotspots (e.g. AT&T at Starbucks) are open WiFi Access points, which means, everyone can connect and the traffic between the mobile device and the access point is not encrypted. As a result, if a user accesses web sites or email without SSL, third parties can easily sniff network traffic.
Secondly, users of public WiFi hotspots can be easily deceived into using a portable rogue access point. A portable hotspot can be configured to change the SSID name to be the same as the one of the public hotspot to attract the user. In addition, the hotpot’s DNS server can be configured to change the domain name resolution any rogue web site. For example, a user connected to the rogue hotspot and tries to access his bank site at HTTP://www.banksite.com can be directed to a rogue web site where the user’s bank credentials can be collected by a hacker.
2. Mobile Device Management Security Measures
If you have the luxury of managing your mobile devices using an MDM system, you may consider the following security measures.
Enforce mobile device registration
Policies and workflows should be put in place for easy registration of devices that should be part of your managed device pool.
OS Version Upgrade Management
For MDM-managed devices, new OS versions and security fixes should be regularly reviewed since they often patch security vulnerabilities or bugs. In case it was determined that an OS version upgrade or patch is needed and compatible with existing mobile applications, the IT department can perform the necessary steps to make sure the upgrade is performed on all devices.
OS version upgrades are often scheduled by the hardware vendor in concert with the cell phone service provider. However, on most mobile platforms the user has control to allow or postpone the upgrade. The MDM system can be used to query the device OS version level and identify users that haven’t performed the upgrade.
Device Internal Storage Encryption
The MDM system should enable the encryption of internal device storage for enterprise devices in order to prevent third parties from gaining access to confidential data on the devices.
The encryption algorithm should be sufficiently strong in order to prevent hackers from easily breaking it. For example, AES with 256-bit key is the Advanced Encryption Standard adopted by the U.S. government and approved by the NSA for top secret document and is suitable for this measure.
Every iOS device has a dedicated AES 256 crypto engine built into the DMA path between the flash storage and main system memory, making file encryption highly efficient.
On Android 3.0 AES-128 bit encryption is used. We have not been able to find out which algorithm is used on Android 4 devices and up.
The mobile device should require the user to authenticate upon powering it on. This security measure is to prevent that a lost or stolen device is fully booted and can be tempered with by an unauthorized party.
Screen Lock PIN/Password Enforcement & Complexity
MDM-managed devices should be screen protected with a PIN or password. This security measure will prevent unauthorized third parties from accessing confidential data such as corporate email on a lost/stolen or unattended device.
The PIN or password should be sufficiently complex in order to prevent unauthorized parties to easily guess the credential. Minimum length, mixed case and alphanumeric policies can help to support this security measure.
Recovering lost devices
Devices lost are a potential security risk for misuse and exposure of sensitive data such as PHI. MDM functionality is available to recover lost devices or display them on a map. This functionality might be leveraged in certain cases.
Device lock for lost/stolen devices
Lost or stolen devices should be locked by the MDM system in order to prevent unauthorized parties to access sensitive applications and data on the device. The MDM system can lock the following functionality:
• Device access (screen lock)
• WiFi network access (Android only)
Email Wipe for BYOD Devices
Lost or stolen mobile devices should be partially wiped by the MDM system in order to prevent unauthorized parties to access sensitive information such as corporate email on the device.
Full Wipe for lost/stolen Enterprise Devices
Lost or stolen Enterprise devices should be fully wiped (Email, SD Card, SMS, applications, contacts, calendar) by the MDM system in order to prevent unauthorized parties to access sensitive information transmitted via corporate email on the device.
Disable Visible Password Feature
Some mobile platforms provide a setting to disable visible passwords. This security measure is to prevent bystanders from seeing a user’s password and using it when the device is left unattended or stolen.
Most MDM systems allow to whitelist a number of apps that the user is allowed to install on their mobile devices. This prevents installing malware apps or apps with inappropriate content.
Rogue App Detection
On mobile platforms which do not allow blocking the users to download applications from the App Store (e.g. Android), the MDM system should implement a Rogue App detection policy which triggers an alert to the enterprise mobile device administrator in case any blacklisted applications are detected on the device. This security measure may offer a containment strategy for malware that has been installed on an enterprise device.
3. Securing Client-Server Communication
Securing Client/Server Communication via SSL
Transport Layer Security (TLS) and Secure Sockets Layer (SSL) are cryptographic protocols that provide secure communication over the Internet. TLS and SSL encrypt the segments of network connections above the Transport Layer, using asymmetric cryptography for key exchange, symmetric encryption for privacy, and message authentication codes for message integrity.
The encryption of client/server traffic is imperative for a safe and secure operating environment in order to prevent 3/4G or WiFi network sniffing of sensitive data.
SSL bit rates and key sizes
There are two different types of encryption rates used with SSL: the session key and the public and private key. The public/private key size is determined when the
Certificate Signing Request (CSR) and private key are created. The key size (bit-length) of a public and private key pair determine how easily the key can be cracked with a brute force attack. If a private key is broken, all the connections initiated with it would be exposed to whoever had the key. A key size of 512 bits is considered weak. A key size of 1024 is exponentially stronger. However, it is more and more likely to be broken as computing power increases. Most providers encourage generating 2048-bit keys.
A session key is generated during the SSL handshake process each time someone connects to the website. It is shorter than the public/private key size because the data of only one session is at risk if it is broken and it reduces load on the server. The bitrate that is used is the highest bitrate that both the server and client support. For example, if your Firefox browser supports 256-bit but your web server only supports 128-bit, the SSL connection will be at 128-bit. The session keys are usually between 40-bit and 256-bit. Any session key lower than 128-bit is considered insecure and won’t pass a PCI Security Council Compliance audit. For SSL certificates, session keys of 128 or 256-bit should be used along with SSLv3/TLSv1 protocol enabled on the web server. Lower encryption key sizes such as 40-bit should be avoided.
Verifying Server Identity
The way the SSL/TLS protocol establishes the identity of a server is via a certificate handshake. The server provides a digital certificate or certificate chain to the client which then compares the issuer of the certificate with the root certificates installed on the device. In case the certificate was not signed by a trusted Certificate Authority, the SSL handshake may fail or a warning about the untrusted certificate may be presented to the user.
The SSL certificate authentication mainly verifies that the certificate provided by the server is a valid, trusted Certificate Authority (CA)-signed certificate. However, it does not verify that the certificate subject is the one that the mobile client wanted to communicate with.
For example, if a mobile application is successfully modified to call an unauthorized third party web application server with a valid CA-signed certificate, the SSL authentication may be successful.
In order to verify the identity of the server, upon establishing a server connection, the mobile application should retrieve the subject information from the server certificate (e.g. Common Name) and compare that against an expected string value.
In case the server certificate’s common name does not match the expected string, the communication should be aborted.
Another option that can be used with many HTTP clients, is Certificate Pinning. Certificate Pinning uses the certificate’s public key inside the mobile app to verify that the SSL certificate sent by the server is the one that is expected. NOTE: Certificate Pinning comes with its own set of problems, most importantly managing transitions to new certificates once the old ones expire.
Securing Client/Server Communication via VPN
Virtual Private Networks (VPN) are often used within organizations to allow you to communicate private information securely over a public network. One advantage of using a VPN connection is that it allow any valid remote user to become part of a corporate central network, using the same network scheme and accessing network resources normally part of the central network. Two other advantages are that VPNs use cryptographic protocols that operate on the Internet Protocol Layer of the Internet Protocol Suite (versus SSL which operates on the upper layers) and that it includes the authentication of the client as well as the server. Once the VPN tunnel is established, all application traffic between the device and the server is encrypted.
VPN may provide an alternative or complement to SSL client/server requests primarily for enterprise mobile applications, but it does not provide a valid solution for consumer applications.
4. Authentication & Session Management
User Credentials Should Not be stored on the device
User credentials should not be stored on the mobile device – not in clear-text, hashed, or encrypted form. This security practice is to prevent that unauthorized parties may gain access to the user credentials and misuse them for different purposes.
Securing Web Service Calls
In order to support many mobile application functions it will be necessary to communicate with cloud or backend servers and retrieve data or multimedia content to be displayed on the mobile device (e.g. a list of network providers in a member application). However, data protocols such as REST/JSON do not provide any built-in authentication security. Just like HTTP, these protocols are stateless.
The following security mechanisms can to be added in order to secure web service calls from the mobile client:
1. A way for the server to authenticate the client calling the web service
2. A way to authenticate the web service provider (also covered by verifying the SSL certificate Subject Name)
3. Preventing that a third party can manipulate the conversation between client and server (man-in-the-middle attack)
4. Prevent sending client’s credentials over the network
5. Preserving the message integrity; Preventing that requests or responses are modified by a third party
6. Preventing that the web service request to the enterprise server is replayed by a third party (replay-attack)
There are a variety of protocols/frameworks available for authenticating web services calls, each with their pros and cons. Examining them would exceed the scope of this post. The most prevalent are:
– oAuth, open standard protocol for authentication and authorization and defined by the IETF organization in RFC 5849. The current version of oAuth is 1.0a. oAuth is used by a large variety of companies such as Facebook, Twitter and Google.
– Java Web Tokens (JWT), a JSON-based open standard (RFC 7519) for creating access tokens that assert some number of claims.
User Session Timeouts
In order to prevent access to your mobile apps by unauthorized parties, application should require the user to reauthorize after a certain period of inactivity. Based on a document by ViaForensics on mobile application security, the recommended period of inactivity is 5 minutes.
There are two components of session management that should be considered: server-side and client-side user session management.
1. Server-side user session management
Following the oAuth process flow the mobile application client receives an oAuth token and token secret to access resources on the server. These tokens should not be valid indefinitely in order to prevent misuse by third parties. The Service Provider should expire the oAuth token and token secret at regular intervals.
In case the tokens are expired on the server, the mobile application will receive a HTTP 401 Unauthorized response from the server and if the client user session has not expired, the app can request another oAuth token from the server without asking the user to log in again.
2. Client-side user session management
The mobile application client should also manage a user session based on user activity.
For example, if the user sends the application to the background or logs out, the user session should be expired immediately and the oAuth token and token secret should be discarded and the mobile application should return to the login page. In order to detect that the user is still actively working, a timer (e.g. 5 mins) should be reset, whenever a user opens performs an activity or clicks on one of the buttons inside the mobile applications (e.g. saves a form).
In case a user leaves the mobile application open without user interaction, the client-side user session timer should expire causing the mobile application to discard the authentication token and return to the login page.
5. Protecting Stored Data
Storing sensitive data on the mobile device should be avoided
A simple paradigm for avoiding the unauthorized access of sensitive and confidential data on the mobile device is to avoid storing this type of data whenever possible. Instead, store this type of data on the server and retrieve it when needed.
The temporary storage of sensitive data on the device in encrypted format should only be considered if the functionality is necessary to support the business process and if there is no other technical option available, e.g. (offline work).
Avoid using shared resources
Mobile platforms provide containers and applications to facilitate the sharing of data between applications. Mobile applications should avoid using shared resources to store application data, sensitive or not, in order to prevent the exposure of pieces of information that may be exploited by unauthorized users and applications.
For example, iOS and Android offer contacts/address book applications, calendars, media folders, and shared file systems for sharing information between applications.
Android also offers the concept of SharedPreferences, a container of key/value pairs which can be shared with other applications. For example, a shared preference can be used by a weather forecast application might store user information such as zip code and notification preferences in a Shared Preference and might want to make those setting available to other apps (e.g. a location-based coupon app).
Store data in the appropriate location
Application data that needs to be stored on the file system should be placed in the appropriate protected location:
The designated documents directory for the application, e.g. for iOS
On iOS platforms, if the developer writes temporary files to a publicly writable place (for example, /tmp, /var/tmp,/Library/Caches or another specific place with this characteristic), an attacker may be able to read or modify the files.
Do not store data in the external storage (e.g. SD Card)
As a general guideline, mobile application data sensitive or not, should not be stored on the SD Card for the following reasons:
1. Since these are physically small cards they can easily be stolen without notice.
2. On Android SD Card file systems are in VFAT format which does not support unix-type access permissions.
3. On Android, files stored in external storage are not encrypted even if the device is set up to use disk encryption which poses a big security thread.
Using private setting for Storage Containers
Certain types of application storage components allow for sharing contents between applications. Even when placing non-secure or non confidential information in these types of containers, we recommend explicitly setting the share preferences for the containers to a private mode.
For example, Android offers a component called Shared Preferences for storing key/value pairs. We recommend, setting the shared preference setting to MODE_PRIVATE.<>
Private settings should also be used when creating files on the file system.
Storing credentials in the keystore
In case you have to store credentials on the device (e.g. for offline login), the keystore is the right place to store them. The keystore is an encrypted space managed by the mobile operating system. Both iOS and Android provide convenient APIs to manage application data in the keystore.
Encryption of sensitive data
If you have to store large amounts of sensitive information, you may want to encrypt data to be stored in file systems and databases.
For both types of containers, there are libraries available to transparently encrypt the data to be stored. For example, SQLCipher can be used to encrypt data in SQLite databases on iOS and Android platforms.
Make sure you are using a strong encryption algorithm, such as AES-256.
Generating an Encryption key
In case you decide to encrypt data on the device yourself, you should ensure that you generate a sufficiently strong encryption key.
Symmetric encryption mechanisms such as AES require an encryption key to be used for encryption and naturally the same key for decryption.
An encryption key should be used that has a sufficient bit-length for AES-256 and can be generated from the user credentials without compromising them.
We propose to use Password-Based Key Derivation Function (PBKDF2) as a derivation algorithm for generating encryption keys. PBKDF2 is a key derivation function that is part of RSA Laboratories’ Public-Key Cryptography Standards (PKCS) series. It is used by disk encryption software such as FileVault (Mac OS X) and DiskCrypter (Windows). The recommended minimum number of iterations according to the standard is 1,000. However we may use a higher number of 10,000 iterations if the device performance allows it. The standard recommends a salt length of at least 64 bits.
Protecting Shared Secrets
Shared secrets are passkeys shared between two parties like client and server. On the client-side, they may need to be available to interact with the servier, e.g. a Google Maps API key. In order to prevent those keys to be stolen, they need to be protected inside the app.
In order to protect credentials embedded in the app code, consider using a commercial module such as Dexguard from Guard Square.
If you can’t use a commercial module, you may want to consider hiding the keys in the native layer on Android using JNI. The native libraries are much more difficult to decompile and decypther than decompiled Java code.
Protecting Preference Keys and Values
If you consider using the OS Preferences container to store confidential information, consider writing a wrapper class that encrypts the information to be stored, or use a third party library to encrypt the container – there are several available on GitHub.
Locking down Application Components
Some mobile platforms such as Android facilitate application development by providing application components open to other applications for sharing data and functionality. For example, Android Content Provider’s, Service’s, Broadcast Receivers or Activities default settings are open for other applications to be able to access the component. This is done by an external application or the operating system sending an Intent to access the component. The target application can specify an intent-filter associated with the Activity, Service, etc. but the intent-filter does not represent a security boundary.
Application components such as content providers, services, or activities should be locked down using the ‘exported’ setting in the Android manifest.
Protecting Application Settings and Configuration
iOS developers often store application settings in plist files which can be easily compromised. Android developers usually store settings in a shared preference XML file or SQLite DB which are not encrypted by default and can be read with root permissions. The danger of storing mobile application settings (server URLs, iteration and count for PBKDF2) unencrypted in a shared resource, is that they can be modified by an unauthorized user or application and may lead to exposure of sensitive data.
Application settings should be stored in encrypted file (text file with key/value pairs or XML file) in the application’s private storage area. The settings file can be encrypted using asymmetric AES-256 encryption.
Preventing WebView Redirects
WebView application components act similar to a browser and can be used to load HTML pages and forms. In order to prevent that the WebView is somehow manipulated to load a malicious web site URL, a check should be implemented which verifies that the Web View only loads certain types of requests:
• Requests to load HTML files in the mobile application’s resource directory (local HTML pages)
• Requests to the authorized servers (check domain name)
Code obfuscation is the practice of scrambling the application logic in order to prevent simple reverse engineering. Reverse engineering of unobfuscated app code can provide hackers with valuable insight into how the application works and this understanding can be used to exploit vulnerabilities.
Reverse engineering of Android applications is fairly easy so measures need to be taken to implement code obfuscation. Android apks are basically zip files and Java code and be easily decompiled and read.
On Android, third party modules such as Proguard from Guard Square can be used to obfuscate the code. Although it doesn’t make the code completely unreadable, it makes it significantly more difficult to decypher the meaning, since all class, method, and variable names are renamed and abbreviated to a few characters.
On iOS, the “Strip Linked Product” command in XCode can be used to strip the application binary of debug symbols and method names which makes the reverse engineering harder and reduces the application binary size.
Prevent execution on jailbroken/rooted devices
Jailbreaking on iOS and rooting on Android is the action to disable the operating system’s security mechanisms. For example, in a jailbroken iOS device the ‘seat belt’ sandboxing mechanism to separate applications and data is disabled which may enable malicious applications exploit another applications vulnerabilities. Also, jailbroken devices are able to execute applications that are not signed, which may be malware applications.
On Android, there are several ways to check if the device is rooted, e.g. by checking for the su executable. There are several third party libraries that can be used as well.
Least Privilege Implementation
Mobile application permissions usage should be determined by the “least privilege” which means, that the application should only request permission it really needs. This security measure prevents that if an external user or malicious software gains control over the mobile application, it can then exploit privileges of that application which it may not even need to operate.
Some permissions can harm the user or expose user’s privacy in case they were to be exploited. Examples are:
• Permissions to access the user’s private data
• Permission to read incoming email
• GPS location permissions
• Performing outgoing calls, or
• Sending SMS messages.
Limiting and validation user input
Code injections, buffer overflows, and server-side system faults can be limited by defining the type of user input directly in the different GUI input components. This security measure can be used for iOS, Android, and HTML forms. For example, by limiting the text field size may avoid buffer overflows or SQL errors when updating the value in the enterprise.
Defining an input field to be numeric restricts user input and avoids program errors and buffer overflows when assigning the input value to variables.
Using date type UI controls restricts the user input to the correct date format and avoids data integrity issues.
Preventing SQL Injection
One of the problems with SQL is that it can be manipulated to expose or destroy data or perform actions that were not intended by the original statement. If data is misconstrued to be part of the SQL statement the resulting SQL injection can have difficult to understand consequences, from harmless bugs that annoy users to serious security holes that expose a user’s data.
To avoid SQL injection requests need to clearly delineate between the SQL statement and the data it includes. SQL injection is avoided on platforms like Android by using parameterized queries which distinguish data from query logic explicitly. The ContentProivder’s query(), update(), delete() and Activities’ managedQuery() methods all support parameterization.
Cleanup of temporary data
Upon program exit or user session expiration, the mobile application should clean up any temporary and non persistent data.
• Sensitive cached or in-memory data
• Application log files
• Temporary files
• Any multimedia files such as images, audio, or video files that have been created as part of the user session.
Preventing WebView Caching
Web Views are application components that function like web browsers and may display HTML pages. Similar to web browsers these components provide caching mechanisms (e.g. for cookies, web pages, or images) for performance enhancement.
The concern is that the web view cache which may contain sensitive data can be accessed by an unauthorized user or application.
If security is a major concern, developers should disable web view caching as a security measure.
In addition, the web server HTTP response can be configured to use a ‘no-cache’ caching directive which prevents the Web View component or Mobile Browser to keep track of the URL history.
Mobile operating systems such as iOS or Android offer the ability to copy text into the device’s clipboard. The clipboard content needs to be cleared whenever the application is closed in order to avoid that sensitive or confidential data is pasted from the app to another place after the user session expired.
In case sensitive data of an app needs to be protected, one should consider preventing the user from taking screenshots. Screenshots are stored in an unsecured photo gallery and can be accessed after the app user session is expired.
On Android, the WindowManager.LayoutParams.FLAG_SECURE flag can be used in your BaseActivity class to prevent users from taking screenshots and videos.
Preventing use of custom keyboards
Custom keyboards are modified OS keyboards that can be used within your app, e.g. a keyboard that contains emoticon keys. The danger with custom keyboard apps is that they can record keystrokes and pass them on to a third party.
On both Android and iOS is possible to detect the use of a custom keyboard. One would have to distinguish between system, hardware manufacturer keyboards and custom keyboards.
I hope this high-level overview over ways to make your mobile app more secure has provided you with at least a list of topics to start your research. Thanks for reading.