46
Mobile Security Research Lab Best Practices - Secure Mobile Development for Android and iOS Version: 1.0 Date: July 31, 2017

Secure Mobile Development Best Practices - msr-lab.com · Best Practices – Secure Mobile Development for Android and iOS Mobile Security Research Lab 2 ABOUT MOBILE SECURITY RESEARCH

Embed Size (px)

Citation preview

Mobile Security Research Lab

Best Practices - Secure Mobile Development for Android and iOS

Version: 1.0

Date: July 31, 2017

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 2

ABOUT MOBILE SECURITY RESEARCH LAB AND THIS GUIDE 4

USING THIS GUIDE 4

CODING PRACTICES 5

1. USEOBFUSCATION 52. TESTTHIRD-PARTYLIBRARIES 53. IMPLEMENTANTI-TAMPERTECHNIQUES 64. PREVENTFRAMINGANDCLICKJACKING 75. PROTECTAGAINSTCSRFWITHFORMTOKENS 86. DYNAMICDEBUGGINGATTACK 9

HANDLING SENSITIVE DATA 9

1. SECURELYSTORESENSITIVEDATAINRAM 92. DELETIONOFDATA 103. AVOIDQUERYSTRINGFORSENSITIVEDATA 114. IMPLEMENTSECUREDATASTORAGE 115. USESECURESETTINGFORCOOKIES 136. FULLYVALIDATESSL/TLS 137. PROTECTAGAINSTSSLDOWNGRADEATTACKS 148. LIMITUSEOFUUID 149. TREATGEOLOCATIONDATACAREFULLY 1510. INSTITUTELOCALSESSIONTIMEOUT 1611. IMPLEMENTENHANCED/TWO-FACTORAUTHENTICATION 1612. PROTECTAPPLICATIONSETTINGS 1713. HIDEACCOUNTNUMBERSANDUSETOKENS 1814. IMPLEMENTSECURENETWORKTRANSMISSIONOFSENSITIVEDATA 1915. VALIDATEINPUTFROMCLIENT 1916. AVOIDSTORINGAPPDATAINBACKUPS 20

CACHING AND LOGGING 21

1. AVOIDCACHINGAPPDATA 212. AVOIDCRASHLOGS 223. LIMITCACHINGOFUSERNAME 234. CAREFULLYMANAGEDEBUGLOGS 235. BEAWAREOFTHEKEYBOARDCACHE 246. BEAWAREOFCOPYANDPASTE 25

IOS 26

1. USETHEKEYCHAINCAREFULLY 262. AVOIDCACHEDAPPLICATIONSNAPSHOTS 273. IMPLEMENTPROTECTIONSAGAINSTBUFFEROVERFLOWATTACKS 274. AVOIDCACHINGHTTP(S)REQUESTS/RESPONSES 28

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 3

5. IMPLEMENTAPPTRANSPORTSECURITY(ATS) 296. IMPLEMENTTOUCHIDPROPERLY 29

ANDROID 31

1. ROOTDETECTION 312. IMPLEMENTFILEPERMISSIONSCAREFULLY 313. IMPLEMENTINTENTSCAREFULLY 324. CHECKACTIVITIES 335. USEBROADCASTSCAREFULLY 336. IMPLEMENTPENDINGINTENTSCAREFULLY 347. PROTECTAPPLICATIONSERVICES 348. AVOIDINTENTSNIFFING 359. IMPLEMENTCONTENTPROVIDERSCAREFULLY 3610. FOLLOWWEBVIEWBESTPRACTICES 3711. AVOIDSTORINGCACHEDCAMERAIMAGES 3812. AVOIDGUIOBJECTSCACHING 3913. SIGNANDROIDAPKS 3914. MALICIOUSCODEINJECTION 4015. SCREENHIJACKEXPLOIT 4016. WEBVIEWSECURITY:PASSWORDSTOREINPLAINTEXT 4017. SHAREDOBJECT(.SOFILE)SECURITY 4118. EXPOSUREOFRESOURCESFILES 4119. INDEVICEDENIALOFSERVICEATTACKS 42

SERVERS 42

1. IMPLEMENTPROPERWEBSERVERCONFIGURATION 422. PROPERLYCONFIGURESERVER-SIDESSL 433. USEPROPERSESSIONMANAGEMENT 444. PROTECTANDPENTESTWEBSERVICES 445. PROTECTINTERNALRESOURCES 45

REFERENCE 46

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 4

About Mobile Security Research Lab And This Guide

Mobile Security Research Lab is being setup with the vision to help the market to understand the security status of the mobile apps, as well as to promote on the mobile app security development.

As a joint effort between Hong Kong Wireless Technology Industry Association (WTIA)1 and the Lab, this guide consolidates the knowledge we learnt from partners, industry and past experience. We share the knowledge hoping to help developers make their apps more secure.

The recommendations in this guide are not exhaustive or perfect, and are likely to evolve and get corrected/updated as needed.

If you have questions or feedback, please let us know.

Using This Guide

This guide gives specific recommendations to use during the mobile app development process. Although the descriptions of security recommendations are not exhaustive or perfect, you will get practical advice that you can use to make your apps more secure.

We try to put the recommendations short, precise and easy to understand. The readers should have solid mobile app development experience to understand each one of them. All the recommendations mentioned in this guide are related to app security. Those non-security related items are outside the scope of this guide.

Please refer to Reference at the end of this guide if you want to have further information or guidelines on secure mobile development.

1HongKongWirelessTechnologyIndustryAssociation(http://wtiahk.org/)isanot-forprofit,politically-neutraltradeassociationdedicatedtothewirelessandmobileindustry.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 5

Coding Practices

1. Use Obfuscation Issue

• Reverse engineering apps can provide valuable insight into how your app works. Numerous of information about your app can be retrieved from reverse engineering, which can provide a lot of information about your app logic. Multiple security measures can be effectiveness if reverse engineering is proceeded successfully on your app.

Recommendation

• Implementing obfuscation on your app can provide a new version of source code or machine code that is unreadable for humans. After implementing obfuscation, reading a stack track is difficult or economically infeasible. It will result in increasing the difficulty and time required of reverse engineering.

2. Test Third-Party Libraries Issue

• Third-party libraries are relied heavily by many developers in mobile app development.

• Many developers assume third-party libraries are well-developed and tested, however, third-party libraries can and do contain vulnerabilities and weaknesses.

Recommendation

• Security auditing must thoroughly test third-party libraries as well as the source code of your app including core iOS and Android code and libraries.

• New vulnerabilities or bugs can exist in new version of third-party libraries or OS. Both should be tested like new code of your app.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 6

3. Implement Anti-Tamper Techniques Issue

• Hacker can modify an app, repackage it and publish it to create a phishing app. Backdoor and Ads can be injected into the app, payment SDK can also be replaced to bypass the payment or steal user information. Financial apps and popular apps are always the target of such attack.

Recommendation

• Obfuscation should be implemented into source code to increase the difficulty of reverse engineering as well as source code modification.

• Employ anti-tamper and tamper-detection techniques to make illegitimate app malfunction or prevent it from operating.

• At runtime, using checksum or digital signature to verify the application integrity. When the application is modified, the checksum will be different from original application which indicate that this is an illegitimate application.

• Public key is used for signing an app before it can be released on Google Play. The public key used for signing can be read from the app at runtime, it can be used for verifying with developer's key to check the application integrity.

• The checksum and digital signature used for comparing should also be protected from tampering.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 7

4. Prevent Framing and Clickjacking Issue

• Framing and Clickjacking attack may appear when the app is involved with WebView.

• 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 primary purpose for framing is to trick users into clicking on something different from what they intended to gather confidential information or take control of the affected computer through chained vulnerabilities like Cross Site Scripting. This attack commonly takes the form of a script that is embedded within the source code, which is executed without the user’s knowledge. It can be triggered when users click a button that appears to perform other function.

Recommendation

• The best way to prevent this practice in iOS is to not use WebViews.

• Sending the proper X-Frame-Options HTTP response header that instruct the browser to not allow framing from another webpage. The X-Frame-Options HTTP response header can be configured at webserver level to instructed the browser not to display the responded content in Iframe.

• One mechanism for the prevention of framing leverages client-side JavaScript. Though client-side and therefore not impervious to tampering, this layer does raise the bar for the attacker.

• APIs designed specifically for WebView can be abused to compromise the security of web contents specified inside a WebView. The best way to protect an application and its users against this well-known vulnerability is to:

o Prevent the X-Frame-Option HTTP response header from loading frames that request content hosted on other domain names. However, this mitigation is not applicable when dealing with a compromised host.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 8

o Leverage internal defense mechanisms to ensure that all UI elements load in top level frames; Thus, avoiding serving content through untrusted frames setup at lower levels.

5. Protect Against CSRF with Form Tokens Issue

• CSRF (Cross-site Request Forgery) is an attack that tricks victim into submitting a malicious request to web application in which they're currently authenticated. The malicious request inherits the identity and privileges of the victim to perform undesired action on behalf of the victim. It relies on known or predictable form values and a logged-in browser session.

• CSRF may appear when the app is involved with WebView.

Recommendation

• HTTP GET method should be only used as a safe method, only for insensitive information retrieval and not for changing any account settings.

• A token should be contained in each form submission which is created with the form or at the beginning of session. Validate this token on the server when receiving POST requests to ensure the request is initiated by the user. This capability is provided with major web platforms and can be implemented on forms with minimal custom development.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 9

6. Dynamic Debugging Attack Issue

• Hackers can use GDB, IDA, Ptrace and other debuggers to track running program, view and modify the code or data, analyze and tamper the business logic of the app (i.e., business transaction data and flow).

Recommendation

• On Android, set the value of debuggable flag to be false in AndroidManifest.xml to make the app cannot not be debugged.

• Implement Anti-Tampersolutiontoavoidhackertoruntheappaftermodifying

AndroidManifest.xml.

• Adopt anti-debugging solution to prevent from this attack.

Handling Sensitive Data

1. Securely Store Sensitive Data in RAM Issue

• Data may be stored in RAM when an application is running, the data may not be properly cleared when the user log out or session timeout.

• Attackers can dump the memory of the application to retrieve application data.

• Android stores an application in RAM until the memory is reclaimed, application data like encryption keys may remain in RAM after use.

• Oftentimes, iOS developers will store application settings in plist files which can be compromised in some situations.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 10

Recommendation

• Do not keep sensitive data like user information and encryption keys in memory longer than required.

• Set any variables to be null that sensitive information after use.

• Avoid using immutable objects for sensitive keys or passwords such as in Android java.lang.String and use char array instead.

• Avoid using NSUserDefault to store sensitive data or information as it stores data in plist files.

• If it is necessary to store data in plist file, encrypt the data before storing into plist file. It will increase the difficulty for attackers to get information even if they can look into the plist file.Secure

2. Deletion of Data Issue

• On Android, calling file.delete() will not securely erase the target file, and as long as it is not overwritten it can be carved from a physical image of the device.

• Due to the aggressive management of the NAND Flash memory, traditional approaches to wipe a file generally do not work on mobile devices

Recommendation

• Assume that any data written to disk can be recovered. Encrypting data before saving it into disk can increase the difficulty of hacker to recover information.

• Avoiding store sensitive data on device if not necessary.

• Rewriting the content of file before deleting can also increase the difficulty of hacker to recover information.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 11

3. Avoid Query String for Sensitive Data Issue

• Query string parameters are visible and can often be unexpectedly cached (web history, webserver or proxy logs, etc.)

Recommendation

• Using an unencrypted query string for meaningful data should be avoided.

• Use secure POST to send user data, with XSRF token protection. POST data is not logged by default in areas where query string data can be found. Whether POST or GET, temporary session cookies should be used.

• Encrypting data using a non-zero initialization vector and temporary session keys can also help prevent a replay attack. If necessary, query string data can be encrypted using a temporary session key negotiated between hosts using secure algorithms, such as Diffie-Hellman.

4. Implement Secure Data Storage Issue

• Data on mobile device is vulnerable from attacks and it requires proper technique to secure the data storing in mobile device. The best way is to avoid not store or cache sensitive data on mobile device.

Recommendation

• Do not store sensitive data where possible.

• Reduce the storage of user information.

• Store data only in RAM and clear at application close and session timeout.

• If it is necessary to store sensitive data on the device, additional layer of verified should be implemented. It is not sufficient to just rely on third-party library on data encryption.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 12

• To prevent data from being recovered easily, use a randomly generated key as master key. Require user to supply a passphrase to encrypt the master key. The passphrase should not be stored on the device. Android

• There is no fine-grained permission for external storage (e.g. SD Card). Therefore, all files in external storage can be access by any app by default.

• Encrypt sensitive data before storing into external storage.

• The memory of a running process can be dumped with root access, sensitive data including encryption keys can be found if exist.

• In Android, standard crypto libraries such as AES that can be used to secure data.

• A less secure cipher mode AES-ECB will often be the default cipher mode when selecting the standard cryptographic provider “AES”.

• Best practice is to specify cipher mode as AES-CBC or AES-GCM with a 256-bit key and a random IV generated by SecureRandom which is included in Android. the key should be derived from a passphrase using the well tested PBKDF2 (Password-Based Key Derivation Function).

iOS

• The Data Protection APIs built into iOS, combined with a complex passphrase, can provide an additional layer of data protection, but are not as secure as implementing additional, third-party verified cryptography. To leverage this, files must be specifically marked for protection. Any data not specifically encrypted using Apple’s data protection APIs is stored unencrypted.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 13

5. Use SECURE Setting for Cookies Issue

• Cookie may be transmitted over an insecure connection if it is not marked as "Secure"

• In addition, setting the "HTTPOnly" flag on a cookie prevents attacks such as cross-site scripting (XSS), because the cookie cannot be accessed via the client side (e.g., cannot be accessed using a snippet of JavaScript code).

Recommendation

• The Set-Cookie headers should use the “Secure” and “HTTPOnly” settings. These settings should be applied to all cookies for native and/or web apps.

6. Fully Validate SSL/TLS Issue

• A privileged network attacker can perform a man-in-the-middle attack to an application if it does not validate its connection to servers properly. This means that an attacker would be able to hook and modify traffic between the app and the server.

Recommendation

• Implement certificate pinning to protect against MITM attacks. With this approach, an attacker needs the private keys from the server side to perform a MITM attack against a device for which they do not have physical access.

• Implement certificate pinning to protect against MITM attacks. With this implement, private key of the server is required in a MITM attack. Unauthorized access to the private key should be denied.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 14

7. Protect Against SSL Downgrade Attacks Issue

• In man-in-the-middle attack, SSL/TLS can be bypassed by transparently hijacking and monitoring HTTPS traffic on the network. It eliminating SSL/TLS which creates an unsecured connection between the client and server.

Recommendation

• Due to the fact that downgrading attack required an initial plaintext to be an entry point to start, serve all traffic over TLS can eliminate the possibility of this attack.

• Validate that if SSL/TLS is active though JavaScript. If an HTTP connection is not detected, the client redirects to HTTPS.

8. Limit Use of UUID Issue

• Universal Unique Identifier (UUID) is assigned by the manufacture of the device to provide a method to identify the mobile device.

• There is a risk of exposing the data of device's previous owner to a new owner if your app only identifies a user by UUID. After resetting a mobile device, a device's new owner can retrieve previous owner data though online even if all user data had been erased locally if the application only identify users by UUID. An attacker can also fake a UUID to pretend as a different user.

Recommendation

• Avoid the use of any identifier provided by device to identify the device. Create a unique device identifier at the time of registration, installation, or first execution. This unique device identifier in combination with user authentication could be required to create a session. The device identifier could also be used as an additional factor in an encryption function.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 15

• By leveraging a challenge-response approach, the server and device can authenticate each other before performing user authentication. It will increase the difficulty of exploitation because the whole authentication process is not only relying on predictable data (e.g. UUID).

9. Treat Geolocation Data Carefully Issue

• GPS is used to provide user location in Android and iOS. There will be a privacy concern if GPS data is mishandling which may put the user in a risk of vulnerable to other attacks if user current or pervious position is known by the attacker.

• Information about local Bluetooth and/or NFC/RFID tags may also leak geolocation information.

• Also, applications with access to gallery pictures can also be grabbing the GPS position stored in them.

Recommendation

• For better privacy use, application should avoid storing GPS data.

• Avoid some application use GPS automatically.

• Do not activate GPS in applications that will run at or near secure locations.

• When working in secure locations, remember that GPS data may be reported back to Apple and Google servers to increase accuracy.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 16

10. Institute Local Session Timeout Issue

• Mobile devices are easily lost or stolen, and an attacker can take advantage of an active session to access sensitive data, execute transactions, or perform reconnaissance on a device owner’s accounts. In addition, without a proper session timeout, an app may be susceptible to data interception via a man-in-the-middle attack.

Recommendation

• Terminate the session after the user is inactive for a period, redirect the user to log-in screen to require the authentication process again. Make sure no data is visible before the authentication is success again.

• Clear all user data associated memory after session timeout.

• Create session and timeout mechanism on both server side and client side, make sure sessions are synchronized.

11. Implement Enhanced / Two-Factor Authentication Issue

• Weak authentication method can grant an attacker unauthorized access to an app easily.

• Passwords created by humans are always easily guessable.

• Passwords can be captured by keyloggers.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 17

Recommendation

• Require complex passwordso Including length of at least six alphanumeric characters (more characters

is always stronger). o Including lowercase characters, uppercase characters, numbers and

symbols.

• Implement two-factor authentication.

• Options for enhanced authentication include: o One-time pin code or passphrase provided by SMS or email -- but beware

that an attacker will likely have access to both on a stolen device

o Password plus additional user-known value, for example user-selected personal factor

o Security questions and answers, selected by the user in advance (e.g. during registration)

• For the higher level of security, use one-time passwords that require the user to not only possess the correct credentials, but also a physical token including the "one time" password.

12. Protect Application Settings Issue

• Plist files are often used by iOS developers for storing application settings which can be compromised in some situations.

• Shared preferences XML file and SQLite database which are not encrypted by default are often used by Android developers. These can be read and modified with root permissions or by using backup procedures.

Recommendation

• Compile settings into the code when possible.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 18

• Include 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.

13. Hide Account Numbers and Use Tokens Issue

• Many apps store complete account numbers in various screens.

Recommendation

• Displaying partial account numbers It helps ensure maximum privacy for this information. Unless there is a need to store the complete number on the device, store the partially hidden numbers.

• Use of tokensInstead of account numbers, tokens can be assigned to each account and provided to the client. These tokens have server-side mapping to an actual account. If the application data be stolen, the user’s account numbers will not be exposed.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 19

14. Implement Secure Network Transmission of Sensitive Data Issue

• Main-in-the-middle attack can be easily performed on an application which no SSL/TSL implementation to secure the data transmission. Any traffic between server and the application can be captured and modify easily.

Recommendation

• Use SSL/TLS either with standard trust validation.

• To prevent the interception of highly sensitive information via a compromised SSL/TLS connection.

• Encrypt highly sensitive values with AES using a key size of 256.

• For hashing purposes, use an algorithm such as SHA-256 or higher.

• On the server side, consider accepting only strong TLS ciphers and keys and disabling lower levels of encryption such as export-grade 40-bit encryption

15. Validate Input from Client Issue

• All input data should be untrusted, even if data is coming from your app. It is possible to 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.

Recommendation

• Services must thoroughly filter and validate input from the app and user.

• Properly sanitize all user input before transmitting and during receipt.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 20

16. Avoid Storing App Data in Backups Issue

• Data stored within an app’s private directory can be potentially retrieved by performing a backup of the data on an Android or iOS device.

Recommendation

Android

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.

Set the allowBackup flag to be false in AndroidManifest.xml to exclude the application from backup and restore infrastructure even in a full system backup

iOS

In performing an iTunes backup of a device on which an app has been installed, the backup will include all subdirectories (except the “Caches” subdirectory) and files contained within that app’s private directory on the device’s file system. Therefore, avoid storing any sensitive data in plaintext within any of the files or folders within the app’s private directory or subdirectories

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 21

Caching and Logging

1. Avoid Caching App Data Issue

• Developers often overlook the ways data can be stored, log/debug log files, cookies, web history, web cache, property lists, files and SQLite databases. These data can be captured by attackers.

Recommendation

• Avoid data caching on device

If possible, do not store cache data. This is the best way to avoid data compromise on the device.

• Prevent HTTP caching

Developers can configure iOS and Android to not cache web data, particularly HTTPS traffic. In iOS consider implementing an NSURLConnection delegate and disabling newCachedResponse.

• Avoid caching of URL history

URL history and page data for any Web process such as online registration.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 22

• Disable auto complete on browsers

For Web applications, HTML form setting to instruct browsers not to cache values. The avoidance of caching should be validated through forensic examination of device data after app utilization.

2. Avoid Crash Logs Issue

• If an app crashes, the resulting log can provide valuable info to an attacker.

Recommendation

• 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.

• Disable NSAssert o Consider disabling NSAssert for iOS. Also, avoid sending crash logs over

the network in plaintext.

• Use secure development tools o Use secure development tools like clang-analyzer, coverity, ASAN and

other utilities to identify all possible operations that can make the app crash or missfunction.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 23

3. Limit Caching of Username Issue

• At runtime, the username is loaded into memory before any type of authentication occurs, allowing potential for a malicious process to intercept the username.

Recommendation

• It is difficult to offer the user convenience of a stored username while avoiding leakage of such information either through insecure storage or potential interception at runtime.

• Replace the username with hash value o Store a masked username instead of the actual username, and replace the

username value in authentication with a hash value. The hash value can be created including a unique device token stored on registration.

4. Carefully Manage Debug Logs Issue

• Debug logs are generally designed to be used to detect and correct flaws in a developing application. These logs can leak sensitive information that may help an attacker create a more powerful attack.

Recommendation

• Generally, we recommend that debug logs are disabled in production.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 24

5. Be Aware of the Keyboard Cache Issue

• iOS logs what users type to provide features such as customized auto-correct and form completion, but sensitive data may also be stored.

• The cache’s contents are beyond the administrative privileges of the application, and so the data cannot be removed from the cache by the application.

Recommendation

• Disable the auto-correct feature for any sensitive information, not just for password fields. Since the keyboard caches sensitive information, it may be recoverable.

• Clear keyboard dictionary o Add an enterprise policy to clear the keyboard dictionary at regular

intervals.

• Special permission for user dictionary o Android contains a user dictionary, where words entered by a user can be

saved for future auto-correction.

• Implementing a custom keyboard or PIN entry

• Disable caching and provide additional protection against malware.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 25

6. Be Aware of Copy and Paste Issue

• Both iOS and Android support copy/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.

Recommendation

• 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.

• On iOS consider whether the user will need to copy/paste data within the app or system-wide, and choose the appropriate type of pasteboard.

• In addition, it can be interesting to clear the clipboard after taking the contents, to avoid other apps read them and leak what the user is doing.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 26

iOS

1. Use the Keychain Carefully Issue

iOS provides the keychain for secure data storage. However, the keychain can be decrypted in several scenarios.

• In iOS7 or below, the keychain can be decrypted if an attacker has access to the encrypted iTunes backup.

• In a jailbreak device, any application can potentially read every other application’s keychain items.

Recommendation

• use protection class (as defined by the kSecAttrAccessible attribute) when storing data in the keychain,.

• To prevent the exposure of keychain items via iTunes backup, use the ThisDeviceOnly protection class where practical.

• For highly sensitive data, consider to use application-level encryption to the keychain.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 27

2. Avoid Cached Application Snapshots Issue

• iOS will store screenshot for visual interface animation when application suspended. These images can often contain user and application sensitive data.

Recommendation

• Blocking cache of application snapshots using API configuration or code can protect sensitive data.

• The snapshot is taken after applicationDidEnterBackground: method returns. To remove sensitive information, this method should be overridden before it returns.

3. Implement Protections Against Buffer Overflow Attacks Issue

• The following three practices help developers how to mitigate the risk of buffer overflow attacks.

o automatic reference counting (ARC) o address space layout randomization (ASLR) o stack-smashing protection.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 28

Recommendation

• Enable ARC

• Compile the application with option -PIE for PIE support. (on iOS 4.3 or later)

• Compile the application with the -fstack-protector-allcompiler

4. Avoid Caching HTTP(S) Requests/Responses Issue

• In the Cache.db file, NSURLRequest will cache responses by default. Caching should be explicitly disabled to prevent this insecure behavior.

Recommendation

• The cachePolicy property of the NSURLRequest can be set to disable the caching of HTTP(S) requests and responses.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 29

5. Implement App Transport Security (ATS) Issue

• In iOS 9, App Transport Security (ATS) helps forced to use HTTPS (TLS v1.2) between an app and any back-end server(s). It is enabled by default after iOS 9.0 SDK.

• Implementing ATS includes a couple of options: o A developer can enable ATS globally (by linking to iOS 9.0 or later SDK)

and then choose to decrease ATS restrictions on a specific server using an exception key

o A developer can disable ATS globally (by setting the NSAllowsArbitraryLoads key to YES) and then use an exception to increase ATS restrictions on a specific server

Recommendation

• For application running on iOS 9.0 or higher, enable ATS and DO NOT set the NSAllowsArbitraryLoads key to Yes or True.

• Developers can use these subkeys NSAllowsArbitraryLoadsInWebContent, NSAllowsLocalNetworking and more in iOS 10 to disable only certain restrictions rather than overriding all ATS restrictions.

6. Implement Touch ID Properly Issue

• Touch ID allow user to authenticate their application using a fingerprint

• When a developer implements Touch ID in their app, they typically do so in one of two ways:

o Using only the Local Authentication framework to authenticate the user. o This method leaves the authentication mechanism vulnerable to bypass.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 30

o An attacker can modify the local check at runtime, or by patching the binary. This is done by overriding the LAContextevaluatePolicy:localizedReason:reply method implementation.

o Using Keychain access control lists (ACLs).

Recommendation

• When using Touch ID, store the app’s secret in the Keychain with an ACL. With this method, iOS performs a user presence check before reading and returning Keychain items to the app.

• Application can read LAContext.evaluatedPolicyDomainState to check whether the evaluatedPolicyDomainState value has changed after iOS 9. If the value has changed, it indicates that Touch ID enrollment changes have occurred since it was last accessed.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 31

Android

1. Root detection Issue

• Hackers can perform lots of malicious activities such as installing malware, modifying the device setting, monitoring app activities (to get confidential information) on a rooted device.

Recommendation

• Checking the existing of su binaries. The existing of su binaries usually mean that the device is rooted.

• Checking the existing of superuser. The existing of superuser usually mean that the device is rooted.

• Checking the BUILD tag for test-keys. Stock Android ROMs from Google are built with release-keys tags by default. The existing of test-key tag indicates that the Android build is either an unofficial build or a developer build.

• Detect whether the device is running on a rooted device or not. Application should check for the root-access and stop running if the device is rooted.

2. Implement File Permissions Carefully Issue

• Sensitive information can be leaked via world readable files.

• An attacker can influence an application behavior by modifying the data of world writeable files read by the application.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 32

Recommendation

• Do not create files with permissions of MODE_WORLD_READABLE or MODE_WORLD_WRITABLE unless it is necessary as any app would be able to read or write the file even though it may be stored in the app’s private data directory. Both modes were deprecated in Android API 17. A SecurityException will be triggered at runtime if there is user of either mode though the restriction is not yet fully enforced.

• Do not use modes such as 0666, 0777, and 0664 with the chmod binary or syscalls accepting a file mode (chmod, fchmod, creat, etc)

3. Implement Intents Carefully Issue

• Improper implementation of intent could result in data leakage, restricted functions being called and program flow being manipulated.

Recommendation

• Android application components accessed via Intents can be public or private. For activity, service and broadcast receiver, the default is dependent whether the component containers intent filters. For ContentProviders, the default is true if minimum required API level or targets API level is lower than 17. The component to be or become public it is misconfigured. To prevent the component be accessed publicly, set the android:exported flag as false in the AndroidManifest.xml to prevent this.

• Public components declared in the Manifest are by default open so any application can access them. If a component does not need to be accessed by all other apps, consider setting a permission on the component declared in the Manifest.

• Data received by public components cannot be trusted and must be scrutinized.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 33

4. Check Activities Issue

• 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 bypassing a password lock screen to access data or functionality.

Recommendation

• Implement internal application state and verify it before further processing to ensure the activity is loaded properly.

5. Use Broadcasts Carefully Issue

• If no permission is set when sending a broadcast Intent, then any unprivileged app can receive the Intent unless it has an explicit destination.

• An attacker could take advantage of an Intent that doesn't have any set permissions in the following way:

o Create a malicious app that includes a component with the e name as a legitimate component

o If that name (or namespace) is not already in use, the malicious app will install on the target device

o Extract sensitive data from the broadcast Intent sent to that component name"?

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 34

Recommendation

• 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.

6. Implement PendingIntents Carefully Issue

• With a PendingIntent, an app can pass an Intent to a second application that can then execute that Intent as if it were the originating app (i.e., with the e permissions). This allows other apps to call back to the originating app's private components.

• The external app, if malicious, may try to influence the destination integrity.

Recommendation

• Use PendingIntents as delayed callbacks to private BroadcastReceivers or broadcast activities, and explicitly specify the component name in the base Intent.

7. Protect Application Services Issue

• Services can be invoked by external applications and so should be protected by permissions and export flags.

Recommendation

• Check Permission

A service may have more than one method which can be invoked from an external caller. It is possible to define permissions separately for each method

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 35

and check if the calling package has the corresponding permission by using checkPermission() function.

• Define permission in the AndroidManifest.xml

Alternatively, one could define separate services and secure access with permissions defined in the AndroidManifest.xml.

• Verify the correct service is being called

When calling a service with sensitive data, validate that the correct service is being called and not a malicious service. If you know the exact name of the component to which you wish to connect, specify that name in the Intent used to connect.

• Verify the permission of calling package o Another method is to use checkPermission() again to verify whether

the calling package has the permissions required to receive the desired Intent. The user grants permissions to the app during installation.

8. Avoid Intent Sniffing Issu

• When another application initiates activity by sending a broadcast intent, malicious apps can read the data included in the intent.

Recommendation

• Do not pass sensitive data between apps using broadcast intents. Instead, use explicit intents.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 36

9. Implement ContentProviders Carefully Issue

• 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.

Recommendation

• Declare permissions on content providers o Declare write permissions unless it's necessary. Make sure to set

permissions so that unprivileged apps cannot read the ContentProvider instance unless required.

• Limit access o Limit access to the minimum required for an operation. For example, to

share an instant message with another app that emails that message to a contact, share only that single message and not all instant messages. The record-level delegation feature within content providers allows for the sharing of a specific record or file without sharing the entire database. Once the external app returns to the originating app, the delegation ends.

• Sanitize SQL query o Treat parameters passed to content providers as untrusted input and don't

use them directly in SQL queries without sanitation. Without sanitation, SQL code can be sent via content provider requests. If the SQL code is included in a query, it can return data or give control to an attacker.

• Filter out path traversals o Content providers that serve files based on a file name being passed to the

provider should ensure path traversals are filtered out. For example, if an attacker were to include ../../../filein a request, it could cause the program to read and return data from files the attacker wouldn't otherwise have access to in the context of the application. Additionally, be aware that following symlinks created by an attacker can have similar results.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 37

10. Follow WebView Best Practices Issue

• WebViews can introduce several security concerns and should be implemented carefully.

• Exploitable vulnerabilities arising from the use of the addJavscriptInterfaceAPI have been discovered.

Recommendation

• Disable JavaScript and Plugin support o If they are not needed, explicitly setting them as disabled.

• Disable local file access o This restricts access to the app’s resource and asset directory and mitigates

against an attack from a web page which seeks to gain access to other locally accessible files.

• Disallow the loading of content from third-party hosts o 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.

• Implementing whitelist scheme o A developer may also consider implementing a whitelist scheme by using

the URI class to inspect components of a URI to ensure it matches an entry within a list of approved resources.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 38

11. Avoid Storing Cached Camera Images Issue

• Many of apps can take a picture with their mobile phone's camera and send the image to for their financial institution for deposit. These apps may retain the image in the mobile device's NAND memory even after it is deleted.

Recommendation

• To avoid transmit the image using non-volatile storage on the device where check image artifacts may be left behind. One possible alternative is to:

1. Create a SurfaceView that displays a camera preview or live preview of what the camera sensor is seeing

2. Insert and program a button that when pressed returns the camera preview as a pixel array

3. Finally, convert the pixel array to bitmap, compress it to a .jpg, encode it to Base64, and submit it to the remote location

• This method will only maintain the image in volatile RAM and prevent the caching of the check image in non-volatile storage.

• Specifically, with the Android Camera class, the method takePicture can be used specifying a callback when the .jpg is generated using the Camera.PictureCallback interface. In particular, we are interested in the method “public void onPictureTaken(byte bytes, Camera camera).” Using this technique, it’s possible to use the “bytes” array content, which will contain the photograph in RAM.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 39

12. Avoid GUI Objects Caching Issue

• With multitasking enabled, Android retains application screen in memory. This allows an attacker to navigate back to retained screens which may include sensitive information, such as bank transection records.

Recommendation

• To counter this, a developer has three common options: 1. Quit the app entirely when the user logs out. 2. 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.

3. Nullify the data on a GUI screen before leaving the screen or logging out.

13. Sign Android APKs

Issue

• APKs should be signed correctly with a non-expired certificate.

Recommendation

• Sign a production app with a production certificate, which should be different from the certificate used for debug version.

• 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

• Also, restrict access to the keystore to only those people that absolutely require it

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 40

14. Malicious Code Injection Issue

• Dynamic injection writes the code into the target process where execute by system API via the OS specific mechanism.

• Hackers can inject malicious code into the target process to hook, monitor and obtain sensitive information such as stealing login account, password, alter the target account and amount of transfers through dynamic injection.

Recommendation

• Adopt mobile application security solutions to protect against dynamic injection attack.

15. Screen Hijack Exploit Issue

• Screen hijacking is a form of malicious code that modifies or replaces app program interface to gather information such as username, password, banking and email authentication.

Recommendation

• Adopt anti screen hijack SDK to protect app screen interface from being hijacked.

16. WebView Security: Password Store in Plaintext Issue

• If username and password was saved by default android Webview component feature, the username and password will be stored in app directory: databases/webview.db in plaintext format and exposing those credentials might lead to someone can be elevating authority or root easily.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 41

Recommendation

• Self-inspection: Turn off password storage function of webview component by setting Webview.getSettings (). SetSavePassword (false).

17. Shared Object (.so file) Security Issue

• Shared Objects (.so file) are the dynamic link library file in an APK and Android uses NDK technology to compile C code to .so file to use directly from Java.

• Reverse engineer .so file may lead to leakage of assembly code of core function and even source code, this may case the loss of intellectual property rights, Hacker may be repacking the app for financial gain.

Recommendation

• Adopt .so file protection solution to prevent against reverse engineer to .so files

18. Exposure of Resources Files Issue

• Resource files in an APK include of icons, images, JavaScript files, and JavaScript files may contain important display interfaces and execution information in resource files.

• Exposure of JavaScript file may lead to functional logic leakage and if it is altered, it may be implanted with a phishing page or malicious code and causing user's sensitive information disclosure.

Recommendation

• Encrypting resources files which contain functional logic.

• Adopt resource file protection solution to prevent exposure of resource files.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 42

19. In Device Denial of Service Attacks Issue

• Evaluate whether the components in app are subject to in device denial of service attacks

• Denial of service attack vulnerability may lead to service outage for security protection and monitoring tools, this may also cause the app to be subject to malicious attack and outage, resulting economic loss or loss of customers.

Recommendation

• Self-inspection: Verify the input parameters in Intent, including extra data, null return value, data length, and conversion judgment, to prevent app crash due to abnormal input.

SERVERS

1. Implement Proper Web Server Configuration Issue

• Eliminate information disclosure on web server, because every server information expose to attackers can lead to compromise the server easier.

Recommendation

• Disable verbose errors o In production environment, verbose errors can leak critical information,

such as versions and web framework information.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 43

• Minimum amount of information in server responses o Turn off the default setting of Apache, disable return for the server

information such as the OS platform is running, version number and the plugins information.

• Change any default directories o To improve security, change any website default directories, default logins

and port number of admin platform. Protect website with obfuscation for sensitive pages.

• Authentication with lockout protection

Apply lockout protection on forms authentication to avoid brute force attack.

2. Properly Configure Server-side SSL Issue

Low encryption settings on webserver

• Weak cipher suite

• Weak protocols

Recommendation

• Enable only strong ciphers (128-bit and up)

• Use TLSv1.2

• Avoid weak ciphers, such as: o NULL cipher suite

o Anonymous Diffie-Hellmann

o DES and RC4 because of their vulnerability to crypto-analytical attacks (NOTE: iOS 10 disables RC4 by default)

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 44

• Avoid weak protocols, such as: o SSLv2

o SSLv3 because of its vulnerability to the POODLE attack - CVE-2014-3566 (NOTE: In iOS 10, the Apple Secure Transport API no longer supports SSLv3)

o TLS 1.0 and earlier because the protocols are vulnerable to the CRIME (CVE-2012-4929) and BEAST (CVE-2011-3389) attacks

3. Use Proper Session Management Issue

• Sessions for users are maintained on most apps via a cookie, which can be vulnerable.

Recommendation

• Protect session cookies possible for an attacker to predict, highjack or perform other attacks against the session.

o Keep the server software up-to-date with security patches on session management.

o Use high-security settings in session configuration. o Ensure the size of the session cookie is sufficient.

4. Protect and Pen Test Web Services Issue

• A compromised server has the potential to intercept user credentials and launch other attacks against app users.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 45

Recommendation

• In general, a production web server must be thoroughly tested and hardened against malicious attack.

• Production server software should be updated to the latest versions, and hardened to prevent information disclosures regarding server software and interfaces.

• Authentication forms should not reflect whether a username exists.

• Prevent username harvesting by providing the e response back to the client for both “invalid user/pass combination” and “no such username found” events.

• All login forms and forms/pages exchanging sensitive data should implement and require HTTPS.

• Turn off verbose errors, remove any legacy unnecessary sites or pages, and continually harden Web resources against potential attacks.

5. Protect Internal Resources Issue

• Resources for internal use such as administrator login forms frequently leverage authentication that is not resistant to brute force. For example, HTTP or forms authentication without lockout. Compromise of administration or other internal resources can lead to extensive data loss and other damage.

Recommendation

• Restricted access

o Using firewall rules and network segmentation to restrict login page, admin area or any other resource that does not require public Internet access.

Best Practices – Secure Mobile Development for Android and iOS

Mobile Security Research Lab 46

Reference

No. Document URL

1 Android – Best Practices for

Security & Privacy https://developer.android.com/training/best-

security.html

2 Best Practice Guide (SSL

Implementation) for Mobile

App Development

https://www.hkcert.org/c/document_library/get_file?

uuid=6dc96d10-3af9-4aaa-9aca-

fb81aa5f14bf&groupId=16

3 iOS Security Guide

https://www.apple.com/business/docs/iOS_Security_

Guide.pdf

4 OWASP - Mobile Top 10 2016

https://www.owasp.org/index.php/Mobile_Top_10_2

016-Top_10

5 OWASP - Web Top 10 2017

https://github.com/OWASP/Top10/raw/master/2017/

OWASP%20Top%2010%20-%202017%20RC1-

English.pdfv

6 OWASP - Security Testing

Guidelines for Mobile Apps https://www.owasp.org/images/0/04/Security_Testin

g_Guidelines_for_mobile_Apps_-

_Florian_Stahl%2BJohannes_Stroeher.pdf

7 PCPD - Best Practice Guide for

Mobile App Development https://www.pcpd.org.hk/tc_chi/resources_centre/pub

lications/guidance/files/Mobileapp_guide_c.pdf

8 Security Best Practices for

Mobile Devices

http://smallbusinessbigthreat.com/wp-

content/uploads/2015/11/Security-Best-Practices-for-

Mobile-Devices-.pdf