Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Mobile App Security: Best Practices for App Developers

DZone's Guide to

Mobile App Security: Best Practices for App Developers

Looking to learn some of the best practices for securing your mobile apps? Check out this post to learn more about the top mobile app security practices.

· Security Zone ·
Free Resource

Discover how to provide active runtime protection for your web applications from known and unknown vulnerabilities including Remote Code Execution Attacks.

Security is the key factor that determines the success or failure of an application. Users can rightly demand a secure app environment for their interactions, and it is the onus of developers to deliver solutions with the latest in app security built in.

Here, we go over some of the commonly used methods to protect user data within apps. These include HTTPS, clearing the Cache, and protected and secure local storage.

Use HTTPS Over HTTP

Hypertext Transfer Protocol Secure is a secure version of HTTP. HTTPS has been designed to enable protected and secure communications over a computer network or the Internet. In HTTPS, communication is encrypted using Transport Layer Security (TLS). TLS, an advanced version of Secure Socket Layer (SSL), are cryptographic protocols that ensure the data security and privacy between a server and an application.

On the other hand, HTTP or Hypertext Transfer Protocol is not encrypted, verifiable, or validated. Hackers are, therefore, able to access a user's communication interface, modify it, or establish themselves between an application and a user on either or both sides of a particular communication.

Transport Layer Security employs X.509 certificates, an exchanged symmetric key, and public or private key encryption, allowing it to:

  • Encrypt the content of communications
  • Ensure that an attacker has not modified messages
  • Verify the integrity of communications
  • Verify the authenticity of communications
  • Validate a server’s identity.

Possible Threats

Hackers can utilize their technical abilities in many different ways to gain access to protected systems and networks. Unlike in a browser, users can't verify whether the application is sending details that are unencrypted. If payment data is sent through HTTP, a malicious application, or someone with access to your router Wi-Fi, you  can capture that data and sniff it.

With a tool like the Python packet sniff, here's what you could get.

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|       Ethernet destination address (first 32 bits)            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Ethernet dest (last 16 bits)  |Ethernet source (first 16 bits)|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|       Ethernet source address (last 32 bits)                  |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|        Type code              |                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


Another threat is 'phishing.' Phishing is a type of social engineering where an attacker gains access to a user's personal information, including login details and similar private data. During a phishing attack, the attacker poses as a legal, reputable entity, either via email or another channel of communication and installs malware into a system or network via an attachment or link.

There are also threats known as a Man-In-The-Middle (MITM) attack. MITM attacks usually intercept communication between two parties. A typical example would be communication between a mobile application and a database of sensitive information. A MITM attack allows the attacker to eavesdrop or manipulate the connection with a malicious goal or to bypass any other security measures that may be in place at either end of the communication.

It is routinely suggested that app developers and owners protect their apps using an HTTPS that is irrespective of whether or not the app handles sensitive communication. For newer browsers, HTTPS has now become an essential requirement. Unprotected HTTP requests may unintentionally reveal information about the identity or behavior or users.

Cache Is not Safe

A cache is a software or hardware component that stores different kinds of data. Cached data is quite useful as it can be recalled faster when needed as it's saved in memory or on local storage. Data stored in a cache can be the result of an earlier request or a duplicate of data stored in another location.

Specific to apps, a cache stores elements of websites or apps to enable quicker load time when accessed in the future. App data can include cached data as well as other chunks of information saved earlier. These can consist of a user's login information, preference settings within the app, etc.

A device's cache can ordinarily contain data for all the apps and websites that have been used on the device. It's important for the application developer to refresh the cache at frequent intervals to ensure that login and other personal information are not unknowingly retained where they are not needed.

With mobile operating systems, like iOS and Android, improving with each subsequent update, the need to manually clear the cache is no longer required as the devices empty the cache on their own. Android systems are especially useful as they usually manage the cache effectively.

Possible Threats

Avoid storing data in a cache unless your application has a proper technique to store and delete data. You should also consider preventing HTTP caching. Developers can configure iOS and Android to not cache web data, particularly HTTPS traffic. You should also consider avoiding caching URL history and headers/body for pages that contain sensitive information, like registration, login etc.

The HTTP protocol supports a "no-store" directive that enforces the browser to not cache any part of the response or the request. For input values, setting autocomplete to "off" can avoid caching input values that don't need to be cached.

Apart from the security issues, they can also create bugs that are hard to debug.There can come a time that information stored in the cache is outdated and may no longer be valid. This leads to downloaded apps malfunctioning during regular updates. To resolve errors like this, you should first clear the cache so that invalid or outdated data is removed. This is especially important during the testing phase of an app, or you may end up having to sift through a large number of bugs.

Storage Options in Android/iOS

The section of a file system that stores settings files, media files, and similar files are known as local storage. With Android, there are storage options:

  • Internal file storage: Store private files that are accessible only to the application.
  • External file storage: Stored on an external system that could probably be even removed.
  • Shared preferences: Store a very small amount of data as key/value pairs.
  • Databases: Store data in SQLite databases using a high-level API.
  • Protected Local Storage

    To secure any stored data, it needs to be safe from unauthorized access, accidental or intentional destruction, and corruption or infection. Specific steps need to be taken to secure this data, which includes having a basic understanding of existing threats, preparing the appropriate layers of defense, and regularly monitoring activity logs and taking corrective action when needed.

    In the event your local storage isn't adequately protected, an automated script or a hacker may be able to infiltrate the local memory via the file manager or different addresses.

    If your local storage is adequately protected, your data is encrypted using a key. Encrypted files can be read after a corresponding key, like a password, has deciphered it. Without the right decryption key, a hacker will only receive a meaningless, jumbled code.

    AsyncStorage

    If you're using React Native, you might be accustomed to storing information in AsyncStorage, which is an unencrypted, asynchronous, persistent, key-value storage. Here's an excerpt from the official React Native documentation on Async Storage:

    On iOS, AsyncStorage is backed by native code that stores small values in a serialized dictionary and larger values in separate files. On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.

    Here's how you set data into AsyncStorage:

    _storeData = async () => {
      try {
        await AsyncStorage.setItem('@MySuperStore:key', 'I like to save it.');
      } catch (error) {
        // Error saving data
      }
    }
    
    retrieveData = async () => {
      try {
        const value = await AsyncStorage.getItem('TASKS');
        if (value !== null) {
          // We have data!!
          console.log(value);
        }
       } catch (error) {
         // Error retrieving data
       }
    }


    AsyncStorage was never meant to store anything sensitive, and you should avoid using it for storing any user identifiable data. Instead, there are libraries, like Conceal by Facebook or Android keystore on Android and keychain on iOS.

    Keep Your Eyes Out for Vulnerabilities in Your Dependencies

    The open source code is vulnerable to severe bugs, just like proprietary software. Components that are not maintained are easy targets for vulnerabilities and bugs. Even if an application has tons of users, there is very little assurance of it being free from critical vulnerabilities, although you can expect the community to patch it quickly if such a vulnerability is disclosed. So, the best bet is to go through vulnerability databases and follow security resources to get acquainted with the trends in security.

    Here are some of the popular vulnerability databases:

    1. NVD (National Vulnerability Database): NVD is the U.S. government repository of standards-based vulnerability management data.
    2. CVEDetails: This is a data source of vulnerabilities and issues acquired from various other sources. Each vulnerability will have a CVE score that determines the severity of the disclosure.
    3. Rapid7 Vulnerability database: Apart from that, you can also try security blogs that will help you keep abreast with the latest exploits and how to respond to security flaws. Here are some of the popular security blogs.

    Apart from that, you can also try security blogs that will help you keep abreast with the latest exploits and how to respond to security flaws. Here are some of the popular security blogs.

    1. Cisco's Blog on Security: This is a good place to find all the major security updates and news related to public discloses.
    2. AlienVault's Blog: AlienVault runs a blog on security management and many other topics that are interesting to the InfoSec community.
    3. Exabeam's Security Blog: Exabeam's blog focuses on incident reporting and SIEM (Security Information and Event Management).

    Move the Sensitive Logic to the Server

    API keys may be required when accessing data from different services. These API keys are needed for services, like Navigation with Google Maps or while using the Google search service. These keys help the system identify whether the user is an authorized user of the particular service.

    Keys have a higher level of protection when stored on the server side compared to when stored on the client side. In the instance that the app does not have a server side, the keys are then saved within the app. In cases like this, the keys are saved in code and encrypted with only a limited level of access. However, having these keys stored in the app is a threat in its own right and is only used as a last option.

    Conclusion

    To conclude, security solutions for mobile apps need to provide critical endpoint security to apps irrespective if they are consumer-facing or business productivity apps.

    Generally speaking, iOS, Android and hybrid JavaScript apps are better at providing enhanced user experience and streamlining operations that might be vulnerable to a host of threats. In a zero-trust world, users and businesses need to be protected from the inherent risk of running mobile apps.

    Find out how Waratek’s award-winning application security platform can improve the security of your new and legacy applications and platforms with no false positives, code changes or slowing your application.

    Topics:
    mobile application ,security ,app security ,mobile app development best practices ,tutorial

    Opinions expressed by DZone contributors are their own.

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}