# Security in Mobile Apps

> Mobile app security threats and how to protect your app using OWASP Mobile's 10 best practices.

- Source: https://engineering.verygood.ventures/general-practices/security_in_mobile_apps/

---

Mobile app security is a critical concern for developers and users alike. The [Open Web Application Security Project (OWASP)](https://owasp.org/) maintains industry-accepted mobile application security guidelines that should be followed when building multiplatform mobile applications.

:::danger
By far, the most common security threat is **social engineering**. Be sure to educate your team and create well-defined trust structures which require face-to-face confirmation for any proposed changes that affect security.
:::

## Common Mobile App Security Threats

- **Social Engineering**: is a manipulation tactic that exploits human error to gain unauthorized access to private information, systems, or valuables. In cybercrime, it involves deceiving users into revealing data, spreading malware, or granting access to restricted systems.

- **Malware**: Malicious software intentionally designed to harm, exploit, or compromise a mobile device, its data, or the user. Mobile app malware can take various forms, often disguised as legitimate apps or embedded within apps to deceive users into installing it on their devices.
  - Trojans
  - Spyware
  - Adware
  - Ransomware
  - Banking Malware
  - Keyloggers
  - Rooting/Jailbreaking Tools
  - Worms
  - Backdoors

- **Phishing**: a deceptive attempt by malicious actors to trick users into revealing sensitive information such as login credentials, financial details, or personal data through fraudulent means. Phishing typically relies on **social engineering techniques** to exploit user trust and **manipulate users into taking actions that compromise their security.**
- **Man in the middle attacks (MitM)**: intercepting communication between mobile apps and servers, allowing attackers to eavesdrop or modify data.
- **Data breaches:** Unauthorized access leads to the exposure of sensitive user data. Risks include personal information (PII), credentials, and financial data.
- **Authentication attacks**: attempts by malicious actors to exploit vulnerabilities in the app's authentication mechanisms to gain unauthorized access to user accounts, sensitive data, or application functionality. These attacks target flaws in how the app verifies the identity of its users or systems.
  - Credential Stuffing
  - Brute Force Attacks
  - Phishing Attacks
  - Session Hijacking
  - Man-in-the-Middle (MitM) Attacks
  - Password Reset Exploits
  - OAuth and Token-Based Attacks: Attackers exploit vulnerabilities in OAuth flows or misconfigure token handling to gain unauthorized access.
- **Code tampering**: Unauthorized modification of the mobile app's code, potentially leading to alterations in functionality or the injection of malicious code.
- **Reverse engineering**: Extraction of source code or sensitive information from the mobile app, often to create fake versions of the app.
- **Insufficient API Security**: Inadequate protection of APIs, leading to vulnerabilities such as unauthorized access, injection attacks, and data exposure.
- **Insecure Data Storage**: Weak encryption or improper storage of sensitive data on the device, making it vulnerable to unauthorized access.
- **Insufficient Transport Layer Protection:** Lack of proper TLS encryption during data transmission, exposing information to interception and manipulation.
- **Denial of Service (DoS) Attacks:** Overwhelming a mobile app or API with traffic disrupts its availability, causing service downtime.
- **Unsecured Third-Party Libraries:** Integration of insecure or outdated third-party libraries which introduce vulnerabilities into the mobile app.
- **Poorly Implemented Multi-Factor Authentication (MFA):** Inadequate implementation of MFA, allowing attackers to bypass additional authentication measures.
- **Supply Chain Attacks:** Compromising the security of a mobile app or API through vulnerabilities in its supply chain, including third-party services or components.

## OWASP Guidelines

The **Open Worldwide Application Security Project (OWASP)** is a globally recognized nonprofit organization dedicated to improving the security of software and web applications. Established in 2001, OWASP provides resources, tools, and best practices to help developers, organizations, and security professionals build secure applications and address vulnerabilities effectively.

### OWASP Mobile Top 10 Security Risks in 2024

The OWASP Mobile Top 10 is a list of the most critical security risks for mobile apps and is updated periodically to reflect emerging threats and trends.

The latest version, OWASP Mobile Top 10 2024, highlights the following risks:

![OWASP comparison 2016 vs 2024](./images/owasp_comparison.png)
_Source_: [OWASP Mobile Top 10 2024](https://owasp.org/www-project-mobile-top-10/)

### Improper Credential Usage

Threat agents can exploit hardcoded credentials or improper credential usage in mobile applications by using automated tools, either publicly available or custom-built.

:::danger
If your app requires access to sensitive API's, **you must not include those API keys in the frontend of your app.**

It is impossible to secure any credentials that are shipped with an application, since **the compiled code for frontend applications is subject to reverse engineering** (no matter how clever you think you are).

Instead of shipping sensitive API keys in your app, create a microservice or cloud function which stores the API key securely in your backend (or leverage services like [Approov](https://approov.io/)). Yes, it's extra work — but it's mandatory for sensitive endpoints.
:::

:::tip

- Use the Android Keystore or iOS Keychain to store sensitive user information.
- Use strong encryption and hashing algorithms during credential storage and transmission.
- Avoid weak authentication mechanisms, including common/weak passwords or insecure authentication flows.
  :::

[Dart-crypt](https://github.com/hoylen/dart-crypt) allows you to salt and hash passwords easily.

[Firebase Authentication](https://firebase.google.com/docs/auth) handles a wide variety of common security considerations and eliminates the need for highly sophisticated authentication for small to mid-size projects.

There's also a [Flutter-specific guide to Auth0](https://developer.auth0.com/resources/guides/mobile/flutter/basic-authentication/) if you're leveraging that in your application.

For more information on _Improper Credential Usage_, [refer to the OWASP guide](https://owasp.org/www-project-mobile-top-10/2023-risks/m1-improper-credential-usage.html).

### Inadequate Supply Chain Security

Attackers can exploit vulnerabilities in the mobile app supply chain, such as inserting malicious code during development or exploiting flaws in third-party libraries, SDKs, or hardcoded credentials.

:::tip

- Leverage human-led code review (with automated tests, checks and analyzers).
- Ensure secure app signing and distribution to block malicious actors. Services like [Codemagic](https://codemagic.io/) can drastically simplify the code-signing process.
- Use trusted, validated third-party libraries to minimize risks.
- Implement a process that requires both a human and an automated vulnerability checker (such as dependabot) to review package updates and patches in your codebase.
- Stay up-to-date on supply chain incidents and open source package vulnerabilities.
- Carefully scan pull requests on your open source projects — many open source projects have accidentally merged malicious code by accident.
  :::

You can check the [Software supply chain security for Flutter and its ecosystem video](https://www.youtube.com/watch?v=7LFftXcw1jA) from the Flutter Forward 2023 conference.

The [**SLSA** (Supply Chain Levels for Software Artifacts) security framework](https://slsa.dev/) maintains a check-list of standards and controls to prevent supply chain attacks.

For more information on _Inadequate Supply Chain Security_, [refer to the OWASP guide.](https://owasp.org/www-project-mobile-top-10/2023-risks/m2-inadequate-supply-chain-security.html)

### Insecure Authentication/Authorization

Threat agents that exploit authentication and authorization vulnerabilities typically do so through automated attacks that use available or custom-built tools.

:::tip

- Use server-side authentication.
- Encrypt local data.
- Use device-specific tokens instead of storing passwords or using weak identifiers.
- Make persistent authentication opt-in.
- Avoid weak PINs for passwords.
- Enforce all controls server-side; assume client-side can be bypassed.
- Use biometrics (FaceID, TouchID) for secure access to sensitive data.
- Perform local integrity checks if offline functionality is necessary.
  :::

For more on data safety, check out the [Encryption and Decryption in Flutter](https://medium.com/@laithalsahore19/explore-encrypt-decrypt-data-in-flutter-e1e64c86b0ee) overview.

You can also use [Local Auth](https://pub.dev/packages/local_auth) to integrate biometric authentication.

For more information on _Insecure Authentication/Authorization_, [refer to the OWASP guide](https://owasp.org/www-project-mobile-top-10/2023-risks/m3-insecure-authentication-authorization.html).

### Insufficient Input/Output Validation

Insufficient validation and sanitization of user inputs or network data in mobile apps can lead to critical vulnerabilities, including SQL injection, command injection, and XSS attacks.

:::tip

- Use strict input validation, set length limits, and reject unexpected or malicious input.
- Sanitize output to prevent XSS (cross-site scripting).
- Use parameterized queries to block SQL injection.
- Work with external security vendors which can evaluate and test your application and its servers.
  :::

Use the [Formz](https://pub.dev/packages/formz) package to validate forms in Flutter and prevent incorrect data to be sent to the backend.

For more information on _Insufficient Input/Output Validation_, [refer to the OWASP guide](https://owasp.org/www-project-mobile-top-10/2023-risks/m4-insufficient-input-output-validation.html).

### Insecure Communication

Threat agents can intercept or modify insecure communications transferred between an app and the server.

When creating an app, assume threats can originate from any of the following:

- Adversaries on the same local network (compromised Wi-Fi).
- Unauthorized network devices (malicious routers or proxy servers).
- Malware on the mobile device itself.

:::tip

- Use SSL/TLS for all data transmissions to backend services and third-party entities and avoid mixed SSL sessions.
- Only accept certificates signed by trusted certificate authorities (CA's) and never allow expired or mismatched certificates.
- Use current, industry accepted encryption algorithms with appropriate key lengths (AES-128 is a good start). Encryption algorithms are subject to mathematical analysis: some older algorithms have been identified by mathematicians and experts as being easier to exploit.
- Pin certificates and require SSL chain verification.
- Never transmit sensitive data via unencrypted channels (like SMS or via push notifications).
- During security testing, conduct traffic analysis to verify no plain text data transmissions.
  :::

If you're using Firebase, you can implement [Firebase App Check](https://firebase.google.com/docs/app-check) to protect your backend from unauthorized clients accessing it.

For more on certificates, see [SSL Certificate Pinning in Flutter](https://dwirandyh.medium.com/securing-your-flutter-app-by-adding-ssl-pinning-474722e38518).

You may also use a package called [Http Certificate Pinning package](https://pub.dev/packages/http_certificate_pinning) to add certificate pinning to your app.

For more information on _Insecure Communication_, [refer to the OWASP guide](https://owasp.org/www-project-mobile-top-10/2023-risks/m5-insecure-communication.html).

### Inadequate Privacy Controls

Privacy controls are concerned with protecting personally identifiable information (PII), such as names and addresses, credit card information, email and IP addresses, health information, religion, sexuality, and political opinions.

This information is valuable to attackers for a number of reasons. For example, an attacker could impersonate the victim to commit fraud, misuse the victim's payment details, blackmail the victim with sensitive information, or harm the victim by destroying or tampering with their critical data.

:::tip

- The best way to prevent privacy violations is to minimize the collection and processing of Personally Identifiable Information (PII). This requires a full understanding of the app's PII usage.
- Evaluate whether all personally identifiable information is necessary, whether less sensitive alternatives can be used, or whether personally identifiable information can be reduced, anonymized, or deleted after a certain period. Allow users to consent to the optional use of personally identifiable information with clear awareness of the associated risks.
- Store or transfer PII only when absolutely necessary, with strict authentication and authorization controls. Secure personal data, such as encrypting health information with device TPM keys to protect against sandbox bypasses.
- Threat modeling can identify the most likely privacy risks, focusing security efforts accordingly. Use static and dynamic security tools to uncover vulnerabilities like improper logging or accidental data leakage.
  :::

For more information on _Inadequate Privacy Controls_, [refer to the OWASP guide.](https://owasp.org/www-project-mobile-top-10/2023-risks/m6-inadequate-privacy-controls.html)

### Insufficient Binary Protection

Attackers target app binaries to extract valuable secrets like API keys or cryptographic secrets, access critical business logic or pre-trained AI models, or investigate weaknesses in backend systems. They may also manipulate binaries to access paid features for free, bypass security checks, or insert malicious code. Repackaging attacks can exploit unsuspecting users, such as modifying payment identifiers and redistributing compromised apps to divert payments to attackers. Protecting app binaries is crucial to prevent data theft, fraud, and malicious exploitation.

:::tip

- Apps should only access the minimal information needed to function, as all data in the binary is vulnerable to leaks or manipulation.
- Use obfuscation tools to make binaries incomprehensible. Native compilation, interpreters, or nested virtual machines can further complicate reverse engineering Test obfuscation quality using reverse-engineering tools.
- Obfuscation makes skipping security checks harder. Reinforce local security checks through backend validation and implement integrity checks to detect code tampering, though attackers may still bypass local checks.
- Integrity checks at app launch can detect unauthorized modifications and redistribution. Violations can be reported to remove fake apps from stores, and specialized services are available to support detection and removal efforts.
  :::

Tools and services such as FreeRASP and Approov can help mitigate the likelihood of a compromised app binary or repackaging attack.

- [Approov](https://approov.io/docs/latest/approov-usage-documentation/)
- [FreeRASP](https://pub.dev/packages/freerasp)

This is a great article that talks about how to secure your API Keys.

- [Securing API Keys](https://nshipster.com/secrets/)
- [Obfuscating Dart Code](https://flutter.dev/docs/deployment/obfuscate)

:::caution
There is no such thing as perfect security against app repackaging attacks. API keys and secrets stored on the client side are always vulnerable to extraction through reverse engineering.

To protect sensitive API's, implement a custom-backend which acts as middleware between the app and the sensitive api's so that the API keys never reach the frontend.
:::

More information on _Insufficient Binary Protection_, [refer to the OWASP guide.](https://owasp.org/www-project-mobile-top-10/2023-risks/m7-insufficient-binary-protection.html)

### Security Misconfiguration

Security misconfiguration occurs when mobile apps have improperly configured security settings, permissions, or controls, leading to vulnerabilities and unauthorized access. Threat agents, such as attackers with physical device access or malicious apps, exploit these weaknesses to access sensitive data or execute unauthorized actions within the vulnerable app's context. Proper configuration is crucial to mitigate these risks.

:::tip

- Ensure default settings do not expose sensitive data or unnecessary permissions.
- Do not use hardcoded credentials.
- Request only necessary permissions for the app's functionality.
- Encrypt app communications and implement certificate pinning.
- Turn off debugging features in production apps.
- Prevent app data from being included in device backups.
- Only export activities, content providers, and services that are required.
  :::

:::caution
Don't add permissions that are not necessary for the app to work. It's easy for an attacker to exploit these permissions to gain access to sensitive data.

In general, you want to respect the **principle of least privilege**: only request the permissions that are absolutely necessary for the app to function.
:::

For more information on _Security Misconfiguration_, [refer to the OWASP guide.](https://owasp.org/www-project-mobile-top-10/2023-risks/m8-security-misconfiguration.html)

### Insecure Data Storage

Insecure data storage in mobile apps exposes sensitive information to various threat agents, including skilled attackers, malicious insiders, state-sponsored actors, cybercriminals, script kiddies, data brokers, competitors, and activists. These agents exploit vulnerabilities like weak encryption, insecure storage, and improper handling of credentials.

:::tip

- Employ robust encryption algorithms to protect data at rest and in transit, such as AES-256.
- Use secure communication protocols like HTTPS or SSL/TLS to protect data during transmission.
- Store sensitive data generated on-device in secure locations, such as Keychain on iOS or Keystore on Android to prevent unauthorized access.
- Use strong authentication, role-based access controls, and validate user permissions to limit access to sensitive data.
- Prevent injection attacks by validating and sanitizing user input to ensure only valid data is stored.
- Use secure session tokens, set proper session timeouts, and securely store session data.
- Keep all libraries and dependencies up to date and apply security patches promptly.
- Monitor security advisories and platform updates to address emerging threats and vulnerabilities.
  :::

If you are using Firestore to store your data, be sure to configure the relevant Firestore security rules for your application.

- [Firestore Security Rules](https://firebase.google.com/docs/firestore/security/get-started)

For sensitive data generated on-device, use the **secure storage** package to store sensitive data in Flutter.

- [Secure Storage](https://pub.dev/packages/flutter_secure_storage)

For more information on _Insecure Data Storage_, [refer to the OWASP guide.](https://owasp.org/www-project-mobile-top-10/2023-risks/m9-insecure-data-storage.html)

### Insufficient cryptography

Threat agents exploiting insecure cryptography in mobile apps aim to compromise the confidentiality, integrity, and authenticity of sensitive information. They include attackers targeting cryptographic algorithms or implementations to decrypt sensitive data, malicious insiders manipulating processes or exposing encryption keys, state-sponsored actors conducting cryptanalysis for intelligence gathering, cybercriminals exploiting weak encryption for data theft or financial fraud, and attackers leveraging vulnerabilities in cryptographic protocols or libraries. Mitigating these risks requires robust cryptographic practices and secure implementation.

:::tip

- Use strong and widely accepted encryption algorithms such as AES-256, RSA, or ECC, ensuring key lengths adhere to industry standards for strong cryptographic protection.
- Follow secure key management practices by storing keys securely in key vaults and making use of hardware security modules for trusted access.
- Encryption and decryption processes should utilize established, peer-reviewed libraries to avoid errors associated with custom implementations, as implementing cryptography correctly is incredibly difficult to do and new vulnerabilities are continually identified, even in major projects.
- Encryption keys must be securely stored using operating system-provided mechanisms or hardware-based options and should not be stored in plain text.
- Use secure transport protocols like HTTPS with proper certificate validation to protect data in transit.
- Validate and authenticate the integrity and authenticity of encryption processes using certificates or digital signatures. Regular updates to cryptographic components are essential to mitigate vulnerabilities, supported by security testing such as vulnerability assessments and penetration testing. Follow industry standards and best practices from organizations like NIST and IETF.
- Adopt strong hash functions like SHA-256 or bcrypt, apply salting to hashed passwords to defend against precomputed attack tables, and use _key derivation functions_ like _PBKDF2_ or _scrypt_ to strengthen password-based cryptography and harden your application against brute-force attacks.
  :::

Check out the following guides for hardening your app's cryptography:

- [Cryptography in Flutter](https://medium.com/flutterdevs/cryptography-in-flutter-7b3b1e3b3b3b)
- [Unlocking Secure Flutter Apps: A Guide to Building with Dart's Cryptography](https://30dayscoding.com/blog/building-flutter-apps-with-darts-cryptography)
- [Crypto Package](https://pub.dev/packages/crypto)

For more information on _Insufficient Cryptography_, [refer to the OWASP guide.](https://owasp.org/www-project-mobile-top-10/2023-risks/m10-insufficient-cryptography.html)

## OWASP MAS Checklist

The [**OWASP Mobile Application Security (MAS) Checklist**](https://mas.owasp.org/checklists/) is a comprehensive guide to securing mobile apps against common security threats. The checklist will provide you with a detailed list of security best practices, including secure coding guidelines, secure data storage, secure communication, and secure authentication mechanisms.

## Other OWASP Resources

- [OWASP Mobile Application Security Testing Guide (MASTG)](https://mas.owasp.org/MASTG/)
- [OWASP Mobile Application Security Verification Standard (MASVS)](https://mas.owasp.org/MASVS/)
- [OWASP Mobile Application Security Weakness Enumeration (MASWE)](https://mas.owasp.org/MASWE/)
