deardaniel/secdata-raw huggingface dataset:
OWASP Mobile Application Security Testing Guide: 0x01 Foreword

# Foreword

Welcome to the OWASP Mobile Application Security Testing Guide. Feel free to explore the existing content, but do note that it may change at any time. New APIs and best practices are introduced in iOS and Android with every major (and minor) release, and vulnerabilities are found every day.

If you have feedback or suggestions, or want to contribute, create an issue on GitHub or ping us on Slack. See the [README](https://www.github.com/OWASP/mastg/) for instructions.

**squirrel (noun plural): Any arboreal sciurine rodent of the genus Sciurus, such as S. vulgaris (red squirrel) or S. carolinensis (grey squirrel), having a bushy tail and feeding on nuts, seeds, etc.**

On a beautiful summer day, a group of ~7 young men, a woman, and approximately three squirrels met in a Woburn Forest villa during the OWASP Security Summit 2017. So far, nothing unusual. But little did you know, within the next five days, they would redefine not only mobile application security but the very fundamentals of book writing itself (ironically, the event took place near Bletchley Park, once the residence and workplace of the great Alan Turing).

Or maybe that's going too far, but at least they produced a proof-of-concept for an unusual security book. The Mobile Application Security Testing Guide (MASTG) is an open, agile, crowd-sourced effort made of the contributions of dozens of authors and reviewers from all over the world.

Because this isn't a normal security book, the introduction doesn't list impressive facts and data proving the importance of mobile devices in this day and age. It also doesn't explain how mobile application security is broken, and why a book like this was sorely needed, and the authors don't thank their beloved ones without whom the book wouldn't have been possible.

We do have a message to our readers, however! The first rule of the OWASP Mobile Application Security Testing Guide is: Don't just follow the OWASP Mobile Application Security Testing Guide. True excellence at mobile application security requires a deep understanding of mobile operating systems, coding, network security, cryptography, and a whole lot of other things, many of which we can only touch on briefly in this book. Don't stop at security testing. Write your own apps, compile your own kernels, dissect mobile malware, learn how things tick. And as you keep learning new things, consider contributing to the MASTG yourself! Or, as they say: "Do a pull request".

<img src="Images/summit-team.jpg" width="100%" />
OWASP Mobile Application Security Testing Guide: 0x06d Testing Data Storage

---
masvs_category: MASVS-STORAGE
platform: ios
---

# iOS Data Storage

## Overview

The protection of sensitive data, such as authentication tokens and private information, is key for mobile security. In this chapter, you'll learn about the iOS APIs for local data storage, and best practices for using them.

As little sensitive data as possible should be saved in permanent local storage. However, in most practical scenarios, at least some user data must be stored. Fortunately, iOS offers secure storage APIs, which allow developers to use the cryptographic hardware available on every iOS device. If these APIs are used correctly, sensitive data and files can be secured via hardware-backed 256-bit AES encryption.
OWASP Mobile Application Security Testing Guide: 0x09 Suggested Reading

# Suggested Reading

## Mobile App Security

### Android

- Dominic Chell, Tyrone Erasmus, Shaun Colley, Ollie Whitehous (2015) _Mobile Application Hacker's Handbook_. Wiley. Available at: <https://www.wiley.com/en-us/The+Mobile+Application+Hacker%27s+Handbook-p[PII_REDACTED]506>
- Joshua J. Drake, Zach Lanier, Collin Mulliner, Pau Oliva, Stephen A. Ridley, Georg Wicherski (2014) _Android Hacker's Handbook_. Wiley. Available at: <https://www.wiley.com/en-us/Android+Hacker%27s+Handbook-p[PII_REDACTED]647>
- Godfrey Nolan (2014) _Bulletproof Android_. Addison-Wesley Professional. Available at: <https://www.amazon.com/Bulletproof-Android-Practical-Building-Developers/dp/[PII_REDACTED]>
- Nikolay Elenkov (2014) _Android Security Internals: An In-Depth Guide to Android's Security Architecture_. No Starch Press. Available at: <https://nostarch.com/androidsecurity>
- Jonathan Levin (2015) _Android Internals :: A confectioners cookbook - Volume I: The power user's view_. Technologeeks.com. Available at: <http://newandroidbook.com/>

### iOS

- Charlie Miller, Dionysus Blazakis, Dino Dai Zovi, Stefan Esser, Vincenzo Iozzo, Ralf-Philipp Weinmann (2012) _iOS Hacker's Handbook_. Wiley. Available at: <https://www.wiley.com/en-us/iOS+Hacker%27s+Handbook-p[PII_REDACTED]122>
- David Thiel (2016) _iOS Application Security, The Definitive Guide for Hackers and Developers_. no starch press. Available at: <https://www.nostarch.com/iossecurity>
- Jonathan Levin (2017), _Mac OS X and iOS Internals_, Wiley. Available at: <http://newosxbook.com/index.php>

## Reverse Engineering

- Bruce Dang, Alexandre Gazet, Elias Backaalany (2014) _Practical Reverse Engineering_. Wiley. Available at: <https://www.wiley.com/en-us/Practical+Reverse+Engineering%3A+x86%2C+x64%2C+ARM%2C+Windows+Kernel%2C+Reversing+Tools%2C+and+Obfuscation-p[PII_REDACTED]311>
- Skakenunny, Hangcom _iOS App Reverse Engineering_. Online. Available at: <https://github.com/iosre/iOSAppReverseEngineering/>
- Bernhard Mueller (2016) _Hacking Soft Tokens - Advanced Reverse Engineering on Android_. HITB GSEC Singapore. Available at: <https://web.archive.org/web/[PII_REDACTED]5520/https://gsec.hitb.org/materials/sg2016/D1%20-%20Bernhard%20Mueller%20-%20Attacking%20Software%20Tokens.pdf>
- Dennis Yurichev (2016) _Reverse Engineering for Beginners_. Online. Available at: <https://beginners.re/>
- Michael Hale Ligh, Andrew Case, Jamie Levy, Aaron Walters (2014) _The Art of Memory Forensics._ Wiley. Available at: <https://www.wiley.com/en-us/The+Art+of+Memory+Forensics%3A+Detecting+Malware+and+Threats+in+Windows%2C+Linux%2C+and+Mac+Memory-p[PII_REDACTED]099>
- Jacob Baines (2016) _Programming Linux Anti-Reversing Techniques_. Leanpub. Available at: <https://leanpub.com/anti-reverse-engineering-linux>
OWASP Mobile Application Security Testing Guide: 0x05f Testing Local Authentication

---
masvs_category: MASVS-AUTH
platform: android
---

# Android Local Authentication

## Overview

During local authentication, an app authenticates the user against credentials stored locally on the device. In other words, the user "unlocks" the app or some inner layer of functionality by providing a valid PIN, password or biometric characteristics such as face or fingerprint, which is verified by referencing local data. Generally, this is done so that users can more conveniently resume an existing session with a remote service or as a means of step-up authentication to protect some critical function.

As stated before in chapter ["Mobile App Authentication Architectures"](0x04e-Testing-Authentication-and-Session-Management.md): The tester should be aware that local authentication should always be enforced at a remote endpoint or based on a cryptographic primitive. Attackers can easily bypass local authentication if no data returns from the authentication process.

On Android, there are two mechanisms supported by the Android Runtime for local authentication: the Confirm Credential flow and the Biometric Authentication flow.
OWASP Mobile Application Security Testing Guide: 0x05g Testing Network Communication

---
masvs_category: MASVS-NETWORK
platform: android
---

# Android Network Communication

## Overview

Almost every Android app acts as a client to one or more remote services. As this network communication usually takes place over untrusted networks such as public Wi-Fi, classical network based-attacks become a potential issue.

Most modern mobile apps use variants of HTTP-based web services, as these protocols are well-documented and supported.
OWASP Mobile Application Security Testing Guide: 0x06e Testing Cryptography

---
masvs_category: MASVS-CRYPTO
platform: ios
---

# iOS Cryptographic APIs

## Overview

In the ["Mobile App Cryptography"](0x04g-Testing-Cryptography.md) chapter, we introduced general cryptography best practices and described typical issues that can occur when cryptography is used incorrectly. In this chapter, we'll go into more detail on iOS's cryptography APIs. We'll show how to identify usage of those APIs in the source code and how to interpret cryptographic configurations. When reviewing code, make sure to compare the cryptographic parameters used with the current best practices linked from this guide.

Apple provides libraries that include implementations of most common cryptographic algorithms. [Apple's Cryptographic Services Guide](https://developer.apple.com/library/content/documentation/Security/Conceptual/cryptoservices/GeneralPurposeCrypto/GeneralPurposeCrypto.html "Apple Cryptographic Services Guide") is a great reference. It contains generalized documentation of how to use standard libraries to initialize and use cryptographic primitives, information that is useful for source code analysis.
OWASP Mobile Application Security Testing Guide: metadata

---
# This is the main metadata file.
# Variables below can be overwritten by the local metadata
# file (e.g. Document-fr/metadata.md)

# Custom Template variables (cover, first page, etc.)
version: 'SNAPSHOT' # this will overridden at build time
languagetext: ''

mainfont: 'DejaVu Sans'
sansfont: 'DejaVu Sans'
monofont: 'DejaVu Sans Mono'

# General variables
toc: true
toc-depth: 2
# numbersections: true
# secnumdepth: 2
linkcolor: blue

# Language variables
lang: 'en'

# Latex variables

# Eisvogel Latex variables
# https://github.com/Wandmalfarbe/pandoc-latex-template#custom-template-variables
code-block-font-size: '\tiny'

table-use-row-colors: true
geometry: "top=1cm,left=1cm,right=2cm,bottom=4cm"
---
OWASP Mobile Application Security Testing Guide: index

---
hide:
  - toc
---

# OWASP MASTG

<img src="https://mas.owasp.org/assets/mastg_cover.png" align="right" style="border-radius: 3px; margin: 3em; box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;" width="350px" />

<a href="https://github.com/OWASP/mastg/">:material-github: GitHub Repo</a>

The **OWASP Mobile Application Security Testing Guide (MASTG)** is a comprehensive manual for mobile app security testing and reverse engineering. It describes technical processes for verifying the controls listed in the [OWASP MASVS](https://mas.owasp.org/MASVS) through the weaknesses defined by the [OWASP MASWE](https://mas.owasp.org/MASWE).

<br>

<br>

Start exploring the MASTG:

<!-- markdown-link-check-disable -->
<!-- markdownlint-disable search-replace -->
<a href="knowledge/" class="md-button md-button--primary" style="margin: 5px; min-width: 12em; text-align: center;">:material-book-open-blank-variant-outline:  Knowledge</a>
<a href="tests/" class="md-button md-button--primary" style="margin: 5px; min-width: 12em; text-align: center;">:octicons-codescan-checkmark-24:  Tests</a>
<a href="techniques/" class="md-button md-button--primary" style="margin: 5px; min-width: 12em; text-align: center;">:material-magic-staff:  Techniques</a>
<a href="demos/" class="md-button md-button--primary" style="margin: 5px; min-width: 12em; text-align: center;">:material-flask-outline:  Demos</a>
<a href="tools/" class="md-button md-button--primary" style="margin: 5px; min-width: 12em; text-align: center;">:octicons-tools-24:  Tools</a>
<a href="apps/" class="md-button md-button--primary" style="margin: 5px; min-width: 12em; text-align: center;">:octicons-code-square-24:  Apps</a>
<a href="best-practices/" class="md-button md-button--primary" style="margin: 5px; min-width: 12em; text-align: center;">:material-shield-check:  Best Practices</a>
<!-- markdownlint-disable search-replace -->
<!-- markdown-link-check-enable -->

<br>
OWASP Mobile Application Security Testing Guide: 0x05d Testing Data Storage

---
masvs_category: MASVS-STORAGE
platform: android
---

# Android Data Storage

## Overview

This chapter discusses the importance of securing sensitive data, like authentication tokens and private information, vital for mobile security. We'll look at Android's APIs for local data storage and share best practices.

While it's preferable to limit sensitive data on local storage, or avoid it at all whenever possible, practical use cases often necessitate user data storage. For example, to improve user experience, apps cache authentication tokens locally, circumventing the need for complex password entry at each app start. Apps may also need to store personally identifiable information (PII) and other sensitive data.

Sensitive data can become vulnerable if improperly protected, potentially stored in various locations, including the device or an external SD card. It's important to identify the information processed by the mobile app and classify what counts as sensitive data. Check out the ["Identifying Sensitive Data"](0x04b-Mobile-App-Security-Testing.md#identifying-sensitive-data "Identifying Sensitive Data") section in the "Mobile App Security Testing" chapter for data classification details. Refer to [Security Tips for Storing Data](https://developer.android.com/training/articles/security-tips.html#StoringData "Security Tips for Storing Data") in the Android developer's guide for comprehensive insights.

Sensitive information disclosure risks include potential information decryption, social engineering attacks (if PII is disclosed), account hijacking (if session information or an authentication token is disclosed), and app exploitation with a payment option.

In addition to data protection, validate and sanitize data from any storage source. This includes checking correct data types and implementing cryptographic controls, such as HMACs, for data integrity.

Android offers various [data storage](https://developer.android.com/training/data-storage "Storing Data in Android") methods, tailored to users, developers, and applications. Common persistent storage techniques include:

- Shared Preferences
- SQLite Databases
- Firebase Databases
- Realm Databases
- Internal Storage
- External Storage
- Keystore

Additionally, other Android functions that can result in data storage and should be tested include:

- Logging Functions
- Android Backups
- Processes Memory
- Keyboard Caches
- Screenshots

Understanding each relevant data storage function is crucial for performing the appropriate test cases. This overview provides a brief outline of these data storage methods and points testers to further relevant documentation.
OWASP Mobile Application Security Testing Guide: 0x06g Testing Network Communication

---
masvs_category: MASVS-NETWORK
platform: ios
---

# iOS Network Communication

## Overview

Almost every iOS app acts as a client to one or more remote services. As this network communication usually takes place over untrusted networks such as public Wi-Fi, classical network based-attacks become a potential issue.

Most modern mobile apps use variants of HTTP-based web services, as these protocols are well-documented and supported.
OWASP Mobile Application Security Testing Guide: SUMMARY

# Summary

- [Frontispiece](0x02a-Frontispiece.md)
- [OWASP MASVS and MASTG Adoption](0x02b-MASVS-MASTG-Adoption.md)
- [Acknowledgments](0x02c-Acknowledgements.md)

## Overview

- [Introduction to the OWASP Mobile Application Security Project](0x03-Overview.md)
- [Mobile Application Taxonomy](0x04a-Mobile-App-Taxonomy.md)
- [Mobile Application Security Testing](0x04b-Mobile-App-Security-Testing.md)

## General Mobile App Testing Guide

- [Mobile App Authentication Architectures](0x04e-Testing-Authentication-and-Session-Management.md)
- [Testing Network Communication](0x04f-Testing-Network-Communication.md)
- [Cryptography in Mobile Apps](0x04g-Testing-Cryptography.md)
- [Testing Code Quality](0x04h-Testing-Code-Quality.md)
- [Tampering and Reverse Engineering](0x04c-Tampering-and-Reverse-Engineering.md)
- [Testing User Privacy Protection](0x04i-Testing-User-Privacy-Protection.md)

## Android Testing Guide

- [Platform Overview](0x05a-Platform-Overview.md)
- [Android Basic Security Testing](0x05b-Android-Security-Testing.md)
- [Data Storage on Android](0x05d-Testing-Data-Storage.md)
- [Android Cryptographic APIs](0x05e-Testing-Cryptography.md)
- [Local Authentication on Android](0x05f-Testing-Local-Authentication.md)
- [Android Network Communication](0x05g-Testing-Network-Communication.md)
- [Android Platform APIs](0x05h-Testing-Platform-Interaction.md)
- [Code Quality and Build Settings for Android Apps](0x05i-Testing-Code-Quality-and-Build-Settings.md)
- [Android Anti-Reversing Defenses](0x05j-Testing-Resiliency-Against-Reverse-Engineering.md)

## iOS Testing Guide

- [Platform Overview](0x06a-Platform-Overview.md)
- [iOS Basic Security Testing](0x06b-iOS-Security-Testing.md)
- [Data Storage on iOS](0x06d-Testing-Data-Storage.md)
- [iOS Cryptographic APIs](0x06e-Testing-Cryptography.md)
- [Local Authentication on iOS](0x06f-Testing-Local-Authentication.md)
- [iOS Network Communication](0x06g-Testing-Network-Communication.md)
- [iOS Platform APIs](0x06h-Testing-Platform-Interaction.md)
- [Code Quality and Build Settings for iOS Apps](0x06i-Testing-Code-Quality-and-Build-Settings.md)
- [iOS Anti-Reversing Defenses](0x06j-Testing-Resiliency-Against-Reverse-Engineering.md)

## Appendix

- [Suggested Reading](0x09-Suggested-Reading.md)
OWASP Mobile Application Security Testing Guide: output

                  
                  
┌────────────────┐
│ 1 Code Finding │
└────────────────┘
                                              
    ../MASTG-DEMO-0090/MastgTest_reversed.java
    ❯❱ rules.mastg-android-biometric-invalidated-enrollment
          [MASVS-AUTH-2] Key configured with setInvalidatedByBiometricEnrollment(false). For sensitive    
          operations, keys should be invalidated when biometric enrollment changes to prevent unauthorized
          access by newly enrolled biometrics.                                                            
                                                                                                          
           52┆ keyGenerator.init(new KeyGenParameterSpec.Builder(this.KEY_NAME, 3).setBlockModes("GCM").se
               tEncryptionPaddings("NoPadding").setUserAuthenticationRequired(false).setInvalidatedByBiome
               tricEnrollment(false).setUserAuthenticationParameters(86400,                               
               0).setUserAuthenticationValidityDurationSeconds(86400).build());
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0091

---
platform: android
title: Uses of setInvalidatedByBiometricEnrollment with semgrep
id: MASTG-DEMO-0091
code: [kotlin]
test: MASTG-TEST-0328
---

## Sample

This sample demonstrates the insecure use of [`setInvalidatedByBiometricEnrollment(false)`](https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.Builder#setInvalidatedByBiometricEnrollment(boolean)) when generating cryptographic keys for biometric authentication.

{{ ../MASTG-DEMO-0090/MastgTest.kt # ../MASTG-DEMO-0090/MastgTest_reversed.java }}

## Steps

Run @MASTG-TOOL-0110 rules against the sample code.

{{ ../../../../rules/mastg-android-biometric-invalidated-enrollment.yml }}

{{ run.sh }}

## Observation

The output shows the usage of `setInvalidatedByBiometricEnrollment()`.

{{ output.txt }}

## Evaluation

The test fails because the output shows:

- Line 52: `setInvalidatedByBiometricEnrollment(false)` is called when creating a key for biometric authentication.

For sensitive operations, keys should use `setInvalidatedByBiometricEnrollment(true)` (or rely on the default behavior) to ensure that keys are permanently invalidated when biometric enrollment changes, preventing newly enrolled biometrics from accessing existing encrypted data.
OWASP Mobile Application Security Testing Guide: output

                   
                   
┌─────────────────┐
│ 2 Code Findings │
└─────────────────┘
                                              
    ../MASTG-DEMO-0090/MastgTest_reversed.java
    ❯❱ rules.mastg-android-biometric-event-bound
          [MASVS-AUTH-2] BiometricPrompt.authenticate called without a CryptoObject or key not requiring user
          authentication. Use authenticate(PromptInfo, CryptoObject) with a keystore-backed key configured   
          with setUserAuthenticationRequired(true) for sensitive operations.                                 
                                                                                                             
           52┆ keyGenerator.init(new KeyGenParameterSpec.Builder(this.KEY_NAME, 3).setBlockModes("GCM").se
               tEncryptionPaddings("NoPadding").setUserAuthenticationRequired(false).setInvalidatedByBiome
               tricEnrollment(false).setUserAuthenticationParameters(86400,                               
               0).setUserAuthenticationValidityDurationSeconds(86400).build());                           
            ⋮┆----------------------------------------
          139┆ prompt1.authenticate(new CancellationSignal(), this$0.context.getMainExecutor(), new
               BiometricPrompt.AuthenticationCallback() { // from class:                           
               org.owasp.mastestapp.MastgTest$mastgTest$1$1                                        
          140┆     @Override // android.hardware.biometrics.BiometricPrompt.AuthenticationCallback
          141┆     public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
          142┆         String str;
          143┆         Intrinsics.checkNotNullParameter(result, "result");
          144┆         Log.d("MASTG-TEST", "Test 1: Auth succeeded (no CryptoObject)");
          145┆         authResult1.element = "Authenticated without CryptoObject";
          146┆         DemoResults demoResults = results;
          147┆         Status status = Status.FAIL;
          148┆         str = this$0.secretToken;
             [hid 22 additional lines, adjust with --max-lines-per-finding]
OWASP Mobile Application Security Testing Guide: output

                   
                   
┌─────────────────┐
│ 2 Code Findings │
└─────────────────┘
                                              
    ../MASTG-DEMO-0090/MastgTest_reversed.java
    ❯❱ rules.mastg-android-biometric-validity-duration
          [MASVS-AUTH-2] Key configured with authentication validity duration > 0. For sensitive operations,
          use setUserAuthenticationParameters(0, type) to require authentication for every cryptographic    
          operation.                                                                                        
                                                                                                            
           52┆ keyGenerator.init(new KeyGenParameterSpec.Builder(this.KEY_NAME, 3).setBlockModes("GCM").se
               tEncryptionPaddings("NoPadding").setUserAuthenticationRequired(false).setInvalidatedByBiome
               tricEnrollment(false).setUserAuthenticationParameters(86400,                               
               0).setUserAuthenticationValidityDurationSeconds(86400).build());                           
            ⋮┆----------------------------------------
           52┆ keyGenerator.init(new KeyGenParameterSpec.Builder(this.KEY_NAME, 3).setBlockModes("GCM").se
               tEncryptionPaddings("NoPadding").setUserAuthenticationRequired(false).setInvalidatedByBiome
               tricEnrollment(false).setUserAuthenticationParameters(86400,                               
               0).setUserAuthenticationValidityDurationSeconds(86400).build());