deardaniel/secdata-raw huggingface dataset:
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0017

---
platform: android
title: Use of Hardcoded AES Key in SecretKeySpec with semgrep
id: MASTG-DEMO-0017
test: MASTG-TEST-0212
tools: [semgrep]
code: [java]
---

## Sample

{{ MastgTest.kt # MastgTest_reversed.java }}

## Steps

Let's run our @MASTG-TOOL-0110 rule against the sample code.

{{ ../../../../rules/mastg-android-hardcoded-crypto-keys-usage.yml }}

{{ run.sh }}

## Observation

The rule has identified one instance in the code file where hardcoded keys is used. The specified line numbers can be located in the reverse-engineered code for further investigation and remediation.

{{ output.txt }}

## Evaluation

The test fails because hardcoded cryptographic keys are present in the code. Specifically:

- On line 24, a byte array that represents a cryptographic key is directly hardcoded into the source code.
- This hardcoded key is then used on line 26 to create a `SecretKeySpec`.
- Additionally, on line 30, another instance of hardcoded data is used to create a separate `SecretKeySpec`.
OWASP Mobile Application Security Testing Guide: output

                   
                   
┌─────────────────┐
│ 3 Code Findings │
└─────────────────┘
                           
    MastgTest_reversed.java
    ❯❱ rules.mastg-android-random-apis-insufficient-entropy
          [MASVS-CRYPTO-1] The application makes use of random number generators with insufficient entropy.
                                                                                                           
           22┆ double random1 = new Random().nextDouble();
            ⋮┆----------------------------------------
           23┆ double random2 = 1 + Math.random();
            ⋮┆----------------------------------------
           27┆ password.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz[PII_REDACTED]".charAt(ran
               dom.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz[PII_REDACTED]".length())));
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0007

---
platform: android
title: Common Uses of Insecure Random APIs
id: MASTG-DEMO-0007
code: [java]
test: MASTG-TEST-0204
---

## Sample

{{ MastgTest.kt # MastgTest_reversed.java }}

## Steps

Let's run our @MASTG-TOOL-0110 rule against the sample code.

{{ ../../../../rules/mastg-android-random-apis-insufficient-entropy.yml }}

{{ run.sh }}

## Observation

The rule has identified five instances in the code file where an insecure random number generator is used. The specified line numbers can be located in the original code for further investigation and remediation.

{{ output.txt }}

## Evaluation

Review each of the reported instances.

- Line 12 seems to be used to generate random numbers for security purposes, in this case for generating authentication tokens.
- Line 17 is part of the function `get_random`. Review any calls to this function to ensure that the random number is not used in a security-relevant context.
- Line 27 is part of the password generation function which is a security-critical operation.

Note that line 37 did not trigger the rule because the random number is generated using `SecureRandom` which is a secure random number generator.
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0072

---
platform: android
title: Runtime Use of Asymmetric Key Pairs Used For Multiple Purposes With Frida
id: MASTG-DEMO-0072
code: [kotlin]
test: MASTG-TEST-0308
---

## Sample

This sample uses the code from @MASTG-DEMO-0071 and takes a dynamic approach to intercept the cryptographic operations at runtime (including encryption, decryption, signing, and verification) to demonstrate the misuse of an asymmetric key pair for multiple purposes.

{{ ../MASTG-DEMO-0071/MastgTest.kt }}

## Steps

1. Install the app on a device (@MASTG-TECH-0005)
2. Make sure you have @MASTG-TOOL-0001 installed on your machine and the frida-server running on the device
3. Run `run.sh` to spawn the app with Frida
4. Click the **Start** button
5. Stop the script by pressing `Ctrl+C` and/or `q` to quit the Frida CLI

{{ script.js # run.sh }}

## Observation

The output shows all usages of cryptographic operations.

{{ output.txt }}

Note all `WARNING` messages in the output.

## Evaluation

The test fails because the same asymmetric key pair is used across different groups of cryptographic operations.

A single RSA key pair is performing both encryption and decryption, as well as signing and verification, which violates the requirement that an asymmetric key be restricted to one purpose class.

In the sample output:

- the private key instance (`android.security.keystore2.AndroidKeyStoreRSAPrivateKey`) is consistently identified by the instance ID `@3818961`
- the matching public key instance (`OpenSSLRSAPublicKey`) is identified by its modulus beginning with `a41226cf3ca5b...`

These two objects form one key pair in the Android Keystore. Their appearances across different operations show the misuse.

Following the private key reference `@3818961`, the first usage appears during decryption:

```bash
🔒 *** Cipher.init(Key) HOOKED ***
  encryption/decryption with key: "android.security.keystore2.AndroidKeyStoreRSAPrivateKey@3818961"
  Stack Trace:
    javax.crypto.Cipher.init(Native Method)
    org.owasp.mastestapp.MastgTest.decrypt(MastgTest.kt:145)
```

Later in the output, the same private key instance is used for signing:

```bash
✍️ *** Signature.initSign(PrivateKey) HOOKED ***
  sign/verify with key: "android.security.keystore2.AndroidKeyStoreRSAPrivateKey@3818961"
!!! WARNING: This key is used for multiple, conflicting purposes: encryption/decryption and sign/verify
```

The matching public key, identified by its modulus (`a41226cf3ca5b...`), appears in both encryption:

```bash
🔒 *** Cipher.init(Key) HOOKED ***
  encryption/decryption with key: "OpenSSLRSAPublicKey{modulus=a41226cf3ca5b...
```

And verification:

```bash
✅ *** Signature.initVerify(PublicKey) HOOKED ***
  sign/verify with key: "OpenSSLRSAPublicKey{modulus=a41226cf3ca5b...
```
OWASP Mobile Application Security Testing Guide: output

                   
                   
┌─────────────────┐
│ 6 Code Findings │
└─────────────────┘
                           
    MastgTest_reversed.java
    ❯❱ rules.mastg-android-broken-encryption-modes
          [MASVS-CRYPTO-1] Broken encryption modes found in use.
                                                                
           36┆ Cipher cipher = Cipher.getInstance("AES");
            ⋮┆----------------------------------------
           55┆ Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            ⋮┆----------------------------------------
           76┆ Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            ⋮┆----------------------------------------
           95┆ Cipher cipher = Cipher.getInstance("AES/ECB/ISO10126Padding");
            ⋮┆----------------------------------------
          118┆ Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            ⋮┆----------------------------------------
          141┆ Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0023

---
platform: android
title: Uses of Broken Encryption Modes in Cipher with semgrep
id: MASTG-DEMO-0023
code: [kotlin]
test: MASTG-TEST-0232
---

## Sample

The sample uses broken encryption modes.

{{ MastgTest.kt # MastgTest_reversed.java }}

## Steps

Let's run our @MASTG-TOOL-0110 rule against the sample code.

{{ ../../../../rules/mastg-android-broken-encryption-modes.yaml }}

{{ run.sh }}

## Observation

The rule has identified six instances in the code file where broken encryption modes are used. The specified line numbers can be located in the reverse-engineered code for further investigation and remediation.

{{ output.txt }}

## Evaluation

The test fails since the output contains several instances of the ECB mode of AES in different transformations explicitly or implicitly (ECB is the default mode for AES if not specified).

See @MASTG-TEST-0232 for more information.
OWASP Mobile Application Security Testing Guide: output

                   
                   
┌─────────────────┐
│ 4 Code Findings │
└─────────────────┘
                           
    MastgTest_reversed.java
    ❯❱ rules.mastg-android-broken-encryption-algorithms
          [MASVS-CRYPTO-1] Broken encryption algorithms found in use.
                                                                     
           39┆ Cipher cipher = Cipher.getInstance("DES");
            ⋮┆----------------------------------------
           62┆ Cipher cipher = Cipher.getInstance("DESede");
            ⋮┆----------------------------------------
           81┆ Cipher cipher = Cipher.getInstance("RC4");
            ⋮┆----------------------------------------
          100┆ Cipher cipher = Cipher.getInstance("Blowfish");
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0022

---
platform: android
title: Uses of Broken Symmetric Encryption Algorithms in Cipher with semgrep
id: MASTG-DEMO-0022
code: [kotlin]
test: MASTG-TEST-0221
---

## Sample

The code snippet below shows sample code contains use of insecure encryption algorithms.

{{ MastgTest.kt # MastgTest_reversed.java }}

## Steps

Let's run our @MASTG-TOOL-0110 rule against the sample code.

{{ ../../../../rules/mastg-android-broken-encryption-algorithms.yaml }}

{{ run.sh }}

## Observation

The rule has identified several instances in the code file where broken encryption algorithms are used. The specified line numbers can be located in the reverse-engineered code for further investigation and remediation.

{{ output.txt }}

## Evaluation

The test fails due to the use of broken encryption algorithms, specifically DES, 3DES, RC4 and Blowfish.

See @MASTG-TEST-0221 for more information.
OWASP Mobile Application Security Testing Guide: output

                   
                   
┌─────────────────┐
│ 2 Code Findings │
└─────────────────┘
                           
    MastgTest_reversed.java
    ❯❱ rules.mastg-android-key-generation-with-insufficient-key-length
          [MASVS-CRYPTO] Make sure that the key size is according to security best practices
                                                                                            
           27┆ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
           28┆ generator.initialize(1024, new SecureRandom());
            ⋮┆----------------------------------------
           31┆ KeyGenerator keyGen1 = KeyGenerator.getInstance("AES");
           32┆ keyGen1.init(128);
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0012

---
platform: android
title: Cryptographic Key Generation With Insufficient Key Length
code: [java]
id: MASTG-DEMO-0012
test: MASTG-TEST-0208
---

## Sample

{{ MastgTest.kt # MastgTest_reversed.java }}

## Steps

Let's run our @MASTG-TOOL-0110 rule against the sample code.

{{ ../../../../rules/mastg-android-key-generation-with-insufficient-key-length.yml }}

{{ run.sh }}

## Observation

The rule has identified some instances in the code file where cryptographic keys are being generated. The specified line numbers can be located in the reverse-engineered code for further investigation and remediation.

{{ output.txt }}

## Evaluation

The test fails because the key size of the RSA key is set to `1024` bits, and the size of the AES key is set to `128`, which is considered insufficient in both cases.
OWASP Mobile Application Security Testing Guide: evaluation

Class: android.security.keystore.KeyProtection$Builder, Method: setBlockModes, Block modes: ECB
Class: android.security.keystore.KeyProtection$Builder, Method: setBlockModes, Block modes: ECB
Class: android.security.keystore.KeyGenParameterSpec$Builder, Method: setBlockModes, Block modes: ECB
OWASP Mobile Application Security Testing Guide: output

                  
                  
┌────────────────┐
│ 1 Code Finding │
└────────────────┘
                           
    MastgTest_reversed.java
    ❯❱ rules.mastg-android-asymmetric-key-pair-used-for-multiple-purposes
          [MASVS-CRYPTO-1] Detected usage of KeyGenParameterSpec.Builder. Review the configured purposes to
          ensure key separation (avoid mixing encryption/decryption with signing/verification or wrapping).
                                                                                                           
           83┆ KeyGenParameterSpec.Builder $this$generateKey_u24lambda_u242 = new
               KeyGenParameterSpec.Builder(this.KEY_ALIAS, 15);
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0071

---
platform: android
title: References to Asymmetric Key Pairs Used For Multiple Purposes with Semgrep
id: MASTG-DEMO-0071
code: [java]
test: MASTG-TEST-0307
---

## Sample

This sample generates an RSA key pair using `KeyGenParameterSpec` with multiple purposes: `PURPOSE_SIGN`, `PURPOSE_VERIFY`, `PURPOSE_ENCRYPT`, and `PURPOSE_DECRYPT`. It subsequently uses it for encryption, decryption, signing, and verification.

{{ MastgTest.kt # MastgTest_reversed.java }}

## Steps

Run the @MASTG-TOOL-0110 rule, as defined below, against the sample code.

{{ ../../../../rules/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml }}

{{ run.sh }}

## Observation

The rule flags the constructor call to `KeyGenParameterSpec.Builder` in the decompiled Java code. This includes the key alias and a number representing the combined purposes used during key generation.

{{ output.txt }}

## Evaluation

The test fails because the key is configured for multiple purposes.

In the output, we can see how the constructor receives a combined purpose value of `15`, which is the bitwise OR of `PURPOSE_ENCRYPT` (`1`), `PURPOSE_DECRYPT` (`2`), `PURPOSE_SIGN` (`4`), and `PURPOSE_VERIFY` (`8`).
OWASP Mobile Application Security Testing Guide: output

                   
                   
┌─────────────────┐
│ 2 Code Findings │
└─────────────────┘
                           
    MastgTest_reversed.java
    ❯❱ rules.mastg-android-non-random-use
          [MASVS-CRYPTO-1] The application makes use of non-random sources.
                                                                           
           22┆ int random1 = (int) new Date().getTime();
            ⋮┆----------------------------------------
           24┆ int random2 = c.get(14);
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0008

---
platform: android
title: Uses of Non-random Sources
id: MASTG-DEMO-0008
code: [java]
test: MASTG-TEST-0205
---

## Sample

{{ MastgTest.kt # MastgTest_reversed.java }}

## Steps

Let's run our @MASTG-TOOL-0110 rule against the sample code.

{{ ../../../../rules/mastg-android-non-random-use.yml }}

{{ run.sh }}

## Observation

The rule has identified some instances in the code file where an non-random source is used. The specified line numbers can be located in the original code for further investigation and remediation.

{{ output.txt }}

## Evaluation

Review each of the reported instances.
OWASP Mobile Application Security Testing Guide: output

                   
                   
┌─────────────────┐
│ 2 Code Findings │
└─────────────────┘
                           
    MastgTest_reversed.java
    ❯❱ rules.mastg-android-hardcoded-security-provider
          [MASVS-CRYPTO-1] Explicitly specified security provider found. Do not hardcode a provider unless
          using AndroidKeyStore.                                                                          
                                                                                                          
           71┆ Cipher cipherBC = Cipher.getInstance("AES/GCM/NoPadding", "BC");
            ⋮┆----------------------------------------
           85┆ Cipher cipherCustom = Cipher.getInstance("AES/CBC/PKCS5Padding", "CustomProvider");
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0075

---
platform: android
title: Uses of Explicit Security Providers in Cryptographic APIs with semgrep
id: MASTG-DEMO-0075
code: [kotlin]
test: MASTG-TEST-0312
---

## Sample

The code snippet below shows sample code that demonstrates both insecure and secure usage of security providers in `getInstance` calls.

{{ MastgTest.kt # MastgTest_reversed.java }}

## Steps

Let's run our @MASTG-TOOL-0110 rule against the sample code.

{{ ../../../../rules/mastg-android-hardcoded-security-provider.yaml }}

{{ run.sh }}

## Observation

The rule has identified instances in the code file where a security provider is explicitly specified. The specified line numbers can be located in the reverse-engineered code for further investigation and remediation.

{{ output.txt }}

## Evaluation

Review each of the reported instances:

- Line 71 uses the deprecated "BC" (BouncyCastle) provider with `Cipher.getInstance`. This is deprecated since Android 9 and removed in Android 12.
- Line 85 uses a custom provider "CustomProvider" which may not be regularly updated or patched.

All other cases are correctly handled and do not trigger the rule.
OWASP Mobile Application Security Testing Guide: output


[+] Frida script loaded to detect StrictMode usage and penaltyLog calls.


[*] StrictMode.VmPolicy.Builder.penaltyLog() called


Backtrace:
android.os.StrictMode$VmPolicy$Builder.penaltyLog(Native Method)
android.os.StrictMode$VmPolicy$Builder.build(StrictMode.java:1226)
android.os.StrictMode.initVmDefaults(StrictMode.java:1522)
android.app.ActivityThread.handleBindApplication(ActivityThread.java:6844)
android.app.ActivityThread.handleBindApplication(Native Method)
android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2236)
android.os.Handler.dispatchMessage(Handler.java:106)

[*] StrictMode.setVmPolicy() called


Backtrace:
android.os.StrictMode.setVmPolicy(Native Method)
android.os.StrictMode.initVmDefaults(StrictMode.java:1522)
android.app.ActivityThread.handleBindApplication(ActivityThread.java:6844)
android.app.ActivityThread.handleBindApplication(Native Method)
android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2236)
android.os.Handler.dispatchMessage(Handler.java:106)
android.os.Looper.loopOnce(Looper.java:205)
Policy: [StrictMode.VmPolicy; mask=[PII_REDACTED]]
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0038

---
platform: android
title: Detecting StrictMode Uses with Frida
id: MASTG-DEMO-0038
code: [kotlin]
test: MASTG-TEST-0264
---

## Sample

This sample demonstrates the detection of `StrictMode` uses at runtime using Frida. The app enables a `StrictMode` policy to detect leaked SQLite objects and intentionally leaves a cursor unclosed to trigger the policy.

{{ ../MASTG-DEMO-0037/MastgTest.kt }}

## Steps

1. Install the app on a device (@MASTG-TECH-0005)
2. Make sure you have @MASTG-TOOL-0001 installed on your machine and the frida-server running on the device
3. Run `run.sh` to spawn the app with Frida
4. Click the **Start** button
5. Stop the script by pressing `Ctrl+C`

{{ run.sh # script.js }}

## Observation

The Frida script output reveals the runtime usage of `StrictMode`.

{{ output.txt }}

## Evaluation

The test fails because the Frida script output shows the runtime usage of `StrictMode`, specifically:

- `StrictMode.VmPolicy.Builder.penaltyLog`
- `StrictMode.setVmPolicy`
OWASP Mobile Application Security Testing Guide: MASTG DEMO 0027

---
platform: android
title: Runtime Use of KeyguardManager.isDeviceSecure and BiometricManager.canAuthenticate APIs with Frida
id: MASTG-DEMO-0027
code: [kotlin]
test: MASTG-TEST-0249
---

## Sample

This sample checks if the device has a secure lock screen via `KeyguardManager.isDeviceSecure` and if the device supports strong biometric authentication using `BiometricManager.canAuthenticate`.

{{ MastgTest.kt }}

## Steps

1. Install the app on a device (@MASTG-TECH-0005)
2. Make sure you have @MASTG-TOOL-0001 installed on your machine and the frida-server running on the device
3. Run `run.sh` to spawn the app with Frida
4. Click the **Start** button
5. Stop the script by pressing `Ctrl+C`

{{ run.sh # script.js }}

## Observation

The output reveals the use of `KeyguardManager.isDeviceSecure` and `BiometricManager.canAuthenticate`.

{{ output.txt }}

## Evaluation

The test passes because the output shows the use of `KeyguardManager.isDeviceSecure` and `BiometricManager.canAuthenticate` at runtime. We can see that:

- `KeyguardManager.isDeviceSecure` is called from the file `MastgTest.kt`, class `MastgTest`, method `isDeviceSecure` at line 24.
- `BiometricManager.canAuthenticate` is called from the file `MastgTest.kt`, class `MastgTest`, method `checkStrongBiometricStatus` at line 38.

Note that in this case the output contains file names and even line numbers, but in real-world scenarios, this information may not be available or not be that useful (e.g. when using a production build or when the app is obfuscated). The output is still valuable because it shows that the APIs are being used at runtime.
OWASP Mobile Application Security Testing Guide: output



[*] KeyguardManager.isDeviceSecure() called - RESULT: false


Backtrace:
android.app.KeyguardManager.isDeviceSecure(Native Method)
org.owasp.mastestapp.MastgTest.isDeviceSecure(MastgTest.kt:24)
org.owasp.mastestapp.MastgTest.mastgTest(MastgTest.kt:10)
org.owasp.mastestapp.MainActivityKt.MainScreen$lambda$9$lambda$8(MainActivity.kt:53)
org.owasp.mastestapp.MainActivityKt.$r8$lambda$PhzGLzmkS_ibruOfiTT32AhzWl4(Unknown Source:0)
org.owasp.mastestapp.MainActivityKt$$ExternalSyntheticLambda0.run(D8$$SyntheticClass:0)
java.lang.Thread.run(Thread.java:1012)


[*] BiometricManager.canAuthenticate called with: BIOMETRIC_STRONG (15) - RESULT: BIOMETRIC_ERROR_NONE_ENROLLED (11)

Backtrace:
android.hardware.biometrics.BiometricManager.canAuthenticate(Native Method)
org.owasp.mastestapp.MastgTest.checkStrongBiometricStatus(MastgTest.kt:38)
org.owasp.mastestapp.MastgTest.mastgTest(MastgTest.kt:11)
org.owasp.mastestapp.MainActivityKt.MainScreen$lambda$9$lambda$8(MainActivity.kt:53)
org.owasp.mastestapp.MainActivityKt.$r8$lambda$PhzGLzmkS_ibruOfiTT32AhzWl4(Unknown Source:0)
org.owasp.mastestapp.MainActivityKt$$ExternalSyntheticLambda0.run(D8$$SyntheticClass:0)
java.lang.Thread.run(Thread.java:1012)
OWASP Mobile Application Security Testing Guide: output

                   
                   
┌─────────────────┐
│ 2 Code Findings │
└─────────────────┘
                           
    MastgTest_reversed.java
     ❱ rules.mastg-android-device-passcode-present
          [MASVS-STORAGE] Make sure to verify that your app runs on a device with a passcode set
                                                                                                
           30┆ Object systemService = context.getSystemService("keyguard");
           31┆ Intrinsics.checkNotNull(systemService, "null cannot be cast to non-null type
               android.app.KeyguardManager");                                              
           32┆ KeyguardManager keyguardManager = (KeyguardManager) systemService;
           33┆ return keyguardManager.isDeviceSecure();
            ⋮┆----------------------------------------
           38┆ BiometricManager biometricManager = (BiometricManager)
               this.context.getSystemService(BiometricManager.class);
           39┆ int result = biometricManager.canAuthenticate(15);