deardaniel/secdata-raw huggingface dataset:
OWASP Mobile Application Security Testing Guide: MASTG TECH 0022

---
title: Information Gathering - Network Communication
platform: android
---

Most of the apps you might encounter connect to remote endpoints. Even before you perform any dynamic analysis (e.g. traffic capture and analysis), you can obtain some initial inputs or entry points by enumerating the domains to which the application is supposed to communicate.

Typically, these domains will be present as strings within the binary of the application. One way to do this is to use automated tools such as @MASTG-TOOL-0125 or @MASTG-TOOL-0035.

Alternatively, you can _grep_ for the domain names using regular expressions. To do this, you can target the app binary directly or reverse engineer it and target the disassembled or decompiled code. The latter option has a clear advantage: it can provide you with **context**, as you'll be able to see in which context each domain is used (e.g. class and method).

From here on, you can use this information to derive more insights which might be of use later during your analysis, e.g. you could match the domains to the pinned certificates or the [Network Security Configuration](../../Document/0x05g-Testing-Network-Communication.md#android-network-security-configuration) file or perform further reconnaissance on domain names to know more about the target environment. When evaluating an application, it is important to check the Network Security Configuration file, as often (less secure) debug configurations might be pushed into final release builds by mistake.

The implementation and verification of secure connections can be an intricate process, and there are numerous aspects to consider. For instance, many applications use other protocols apart from HTTP, such as XMPP or plain TCP packets, or perform certificate pinning in an attempt to deter MITM attacks, but unfortunately have severe logical bugs in their implementation or an inherently wrong security network configuration.

Remember that in most cases, just using static analysis will not be enough and might even turn out to be extremely inefficient when compared to the dynamic alternatives, which will get much more reliable results (e.g. using an interceptor proxy). In this section, we've just slightly touched the surface. Please refer to @MASTG-TECH-0010 and also check the test cases in the "[Android Network Communication](../../Document/0x05g-Testing-Network-Communication.md)" chapter.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0127

---
title: Inspecting an App's Backup Data
platform: android
---

You can inspect an Android app's backup data to verify that sensitive data is not included in the backup. This technique is useful for verifying that the app correctly excludes sensitive data from backups.

## Backup Made via @MASTG-TOOL-0004 Backup

Android backups are stored in `.ab` files, which are specially formatted TAR archives. If you followed the steps from @MASTG-TECH-0128, you should have an `apps/` directory in your working directory. This directory contains the extracted backup data.

The files are stored within top-level directories according to their semantic origin:

- `apps/pkgname/a/`: Application .apk file itself
- `apps/pkgname/obb/`: The application's associated .obb containers
- `apps/pkgname/f/`: The subtree rooted at the `getFilesDir()` location
- `apps/pkgname/db/`: The subtree rooted at the `getDatabasePath()` parent
- `apps/pkgname/sp/`: The subtree rooted at the `getSharedPrefsFile()` parent
- `apps/pkgname/r/`: Files stored relative to the root of the app's file tree
- `apps/pkgname/c/`: Reserved for the app's `getCacheDir()` tree; not stored.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0115

---
title: Obtaining Compiler-Provided Security Features
platform: android
---

Run @MASTG-TOOL-0129 on the target binary, for example a shared library and grep for the keywords you'd like to check for.

```sh
rabin2 -I lib/x86_64/libnative-lib.so | grep -E "canary|pic"
canary   false
```
OWASP Mobile Application Security Testing Guide: MASTG TECH 0042

---
title: Getting Loaded Classes and Methods Dynamically
platform: android
---

You can use the command `Java` in the Frida CLI to access the Java runtime and retrieve information from the running app. Remember that, unlike Frida for iOS, in Android, you need to wrap your code inside a `Java.perform` function. Thus, it's more convenient to use Frida scripts, e.g. get a list of loaded Java classes and their corresponding methods and fields, or for more complex information gathering or instrumentation. One such script is listed below. The script to list the class's methods used below is available on [Github](https://github.com/frida/frida-java-bridge/issues/44 "Github").

```js
// Get list of loaded Java classes and methods

// Filename: java_class_listing.js

'use strict';

Java.perform(function () {
  var classes = [];
  var seen = Object.create(null);

  Java.enumerateLoadedClasses({
    onMatch: function (name) {
      if (seen[name]) return;
      seen[name] = true;

      classes.push({
        name: name,
        package: name.indexOf(".") > 0 ? name.substring(0, name.lastIndexOf(".")) : ""
      });
    },
    onComplete: function () {
      console.log(JSON.stringify({
        type: "loaded_classes",
        total: classes.length,
        classes: classes
      }));
    }
  });
});
```

After saving the script to a file called `java_class_listing.js`, you can tell Frida CLI to load it by using the flag `-l` and inject it into the foreground application using the flag `-F`.

```bash
frida -U -q -F -l java_class_listing.js -o classes.json
```

The `classes.json` file will contain the output of the script, which is a JSON object with the total number of loaded classes and an array of class names and their corresponding packages.

```json
{
    "type": "loaded_classes",
    "total": 30914,
    "classes": [
        {
            "name": "org.owasp.mastestapp.MastgTest",
            "package": "org.owasp.mastestapp"
        },
        {
            "name": "java.io.ObjectStreamException",
            "package": "java.io"
        },
        {
            "name": "javax.crypto.IllegalBlockSizeException",
            "package": "javax.crypto"
        },
        ... 
    ]
}
```

Given the verbosity of the output, the system classes can be filtered out programmatically to make the output more readable and relevant to the use case.

For example, use `jq` to filter out classes that belong to the `org.owasp.mastestapp.*` packages:

```bash
jq '.classes[] | select(.package | startswith("org.owasp.mastestapp"))' classes.json
```

Output:

```json
{
  "name": "org.owasp.mastestapp.MastgTest",
  "package": "org.owasp.mastestapp"
}
{
  "name": "org.owasp.mastestapp.BaseScreenKt$BaseScreen$2",
  "package": "org.owasp.mastestapp"
}
{
  "name": "org.owasp.mastestapp.MainActivityKt$MainScreen$2",
  "package": "org.owasp.mastestapp"
}
...
```
OWASP Mobile Application Security Testing Guide: MASTG TECH 0020

---
title: Retrieving Cross References
platform: android
---

## Java and Kotlin

There are many RE tools that support retrieving Java cross references. For many of the GUI-based ones, this is usually done by right clicking on the desired function and selecting the corresponding option, e.g. **Show References to** in Ghidra or [**Find Usage**](https://github.com/skylot/jadx/wiki/jadx-gui-features-overview#find-usage "jadx - find-usage") in @MASTG-TOOL-0018.

## Native Code

Similarly to Java analysis, you can also use Ghidra to analyze native libraries and obtain cross references by right clicking the desired function and selecting **Show References to**.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0145

---
title: Working with XAPK Files
platform: android
---

When downloading apps from alternative stores such as APKPure or APKMirror, you may receive XAPK files instead of a single APK. XAPK is not an Android standard format. It is simply a ZIP archive used by third-party stores to bundle one or more APKs together with optional additional data.

## What an XAPK Contains

An XAPK file is a regular ZIP archive that typically includes:

- A base APK
- Optional split APKs generated from an Android App Bundle
- Optional OBB data files
- A manifest.json file describing the package contents

## Extracting an XAPK

Because XAPK is just a ZIP file, it can be extracted using standard tools.

```bash
unzip app.xapk -d app_extracted
```

After extraction you may see a single APK or multiple APK files. For example:

```sh
ls -1 app_extracted
base.apk
config.ar.apk
config.arm64_v8a.apk
...
config.xxxhdpi.apk
icon.png
manifest.json
```

## Installing Apps from an XAPK

### Single APK Case

If the extracted directory contains only one APK, it can be installed normally.

```bash
adb install app_extracted/*.apk
```

### Split APK Case

If multiple APKs are present, the app was built as an Android App Bundle. There is no reliable or supported way to convert these splits into one universal APK. The correct approach is to install the base APK together with the splits that match the target device.

```bash
adb install-multiple -r app_extracted/*.apk
```

### OBB Data

If the XAPK contains OBB files, install the APKs first, then push the OBB directory to the device.

```bash
adb push app_extracted/Android/obb/<package.name> /sdcard/Android/obb/
```

## Reverse Engineering

For reverse engineering and static analysis, you can open the base APK and all relevant split APKs together using @MASTG-TOOL-0018 like this:

```bash
jadx app_extracted/*.apk
```

See @MASTG-TECH-0017 for more details on decompiling Android apps.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0028

---
title: Get Open Connections
platform: android
---

You can find system-wide networking information in `/proc/net` or just by inspecting the `/proc/<pid>/net` directories (for some reason, not process-specific). There are multiple files present in these directories, of which `tcp`, `tcp6`, and `udp` might be considered relevant from the tester's perspective.

```bash
# cat /proc/7254/net/tcp
sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
...
69: 1101A8C0:BB2F 9A447D4A:01BB 01 00000000:00000000 00:[PII_REDACTED] 10093        0 75412 1 [PII_REDACTED] 20 3 19 10 -1
70: 1101A8C0:917C E3CB3AD8:01BB 01 00000000:00000000 00:[PII_REDACTED] 10093        0 75553 1 [PII_REDACTED] 20 3 23 10 -1
71: 1101A8C0:C1E3 9C187D4A:01BB 01 00000000:00000000 00:[PII_REDACTED] 10093        0 75458 1 [PII_REDACTED] 20 3 19 10 -1
...
```

In the output above, the most relevant fields for us are:

- `rem_address`: remote address and port number pair (in hexadecimal representation).
- `tx_queue` and `rx_queue`: the outgoing and incoming data queue in terms of kernel memory usage. These fields give an indication of how actively the connection is being used.
- `uid`: containing the effective UID of the creator of the socket.

Another alternative is to use the `netstat` command, which also provides information about the network activity for the complete system in a more readable format, and can be easily filtered as per our requirements. For instance, we can easily filter it by PID:

```bash
# netstat -p | grep 24685
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program Name
tcp        0      0 192.168.1.17:47368      172.217.194.103:https   CLOSE_WAIT  24685/com.google.android.youtube
tcp        0      0 192.168.1.17:47233      172.217.194.94:https    CLOSE_WAIT  24685/com.google.android.youtube
tcp        0      0 192.168.1.17:38480      sc-in-f100.1e100.:https ESTABLISHED 24685/com.google.android.youtube
tcp        0      0 192.168.1.17:44833      74.125.24.91:https      ESTABLISHED 24685/com.google.android.youtube
tcp        0      0 192.168.1.17:38481      sc-in-f100.1e100.:https ESTABLISHED 24685/com.google.android.youtube
...
```

`netstat` output is clearly more user-friendly than reading `/proc/<pid>/net`. The most relevant fields for us, similar to the previous output, are the following:

- `Foreign Address`: remote address and port number pair (port number can be replaced with the well-known name of a protocol associated with the port).
- `Recv-Q` and `Send-Q`: Statistics related to receive and send queues. Indicates how actively the connection is being used.
- `State`: the state of a socket, for example, if the socket is in active use (`ESTABLISHED`) or closed (`CLOSED`).
OWASP Mobile Application Security Testing Guide: MASTG TECH 0116

---
title: Obtaining Information about the APK Signature
platform: android
---

## Verify APK Signatures

@MASTG-TOOL-0123 can be used to verify APK signatures:

```bash
$ apksigner verify --verbose example.apk
Verifies
Verified using v1 scheme (JAR signing): false
Verified using v2 scheme (APK Signature Scheme v2): true
Verified using v3 scheme (APK Signature Scheme v3): true
Verified using v3.1 scheme (APK Signature Scheme v3.1): false
Verified using v4 scheme (APK Signature Scheme v4): false
Verified for SourceStamp: false
Number of signers: 1
```

## Additional Signature Information

Additional information about the signature, including fields from the signing certificate, digest, and key information, can also be examined with @MASTG-TOOL-0123:

```bash
$ apksigner verify --print-certs --verbose example.apk
[...]
Signer #1 certificate DN: CN=Example Developers, OU=Android, O=Example
Signer #1 certificate SHA-256 digest: 1fc4de52d0daa33a9c0e3d67217a77c895b46266ef020fad0d48216a6ad6cb70
Signer #1 certificate SHA-1 digest: 1df329fda8317da4f17f99be83aa64da62af406b
Signer #1 certificate MD5 digest: 3dbdca9c1b56f6c85415b67957d15310
Signer #1 key algorithm: RSA
Signer #1 key size (bits): 2048
Signer #1 public key SHA-256 digest: 296b4e40a31de2dcfa2ed277ccf787db0a524db6fc5eacdcda5e50447b3b1a26
Signer #1 public key SHA-1 digest: 3e02ebf64f1bd4ca85732186b3774e9ccd60cb86
Signer #1 public key MD5 digest: 24afa3496f98c66343fc9c8a0a7ff5a2
```
OWASP Mobile Application Security Testing Guide: MASTG TECH 0014

---
title: Static Analysis on Android
platform: android
---

Static analysis is a technique used to examine and evaluate the source code of a mobile application without executing it. This method is instrumental in identifying potential security vulnerabilities, coding errors, and compliance issues. Static analysis tools can scan the entire codebase automatically, making them a valuable asset for developers and security auditors.

Two good examples of static analysis tools are grep and @MASTG-TOOL-0110. However, there are many other tools available, and you should choose the one that best fits your needs.

## Example: Using grep for Manifest Analysis in Android Apps

One simple yet effective use of static analysis is using the `grep` command-line tool to inspect the `AndroidManifest.xml` file of an Android app. For example, you can extract the minimum SDK version (which indicates the lowest version of Android the app supports) with the following `grep` command:

```bash
grep 'android:minSdkVersion' AndroidManifest.xml
```

This command searches for the `android:minSdkVersion` attribute within the manifest file. Ensuring a higher `minSdkVersion` can reduce security risks, as older versions of Android may not include the latest security features and fixes.

## Example: Using semgrep for Identifying Seeds With Insufficient Entropy

semgrep is a more advanced tool that can be used for pattern matching in code. It's particularly useful for identifying complex coding patterns that might lead to security vulnerabilities. For example, to find instances where a deterministic seed is used with the `SecureRandom` class (which can compromise the randomness and thus the security), you can use a semgrep rule like:

```yaml
rules:
  - id: insecure-securerandom-seed
    patterns:
      - pattern: new SecureRandom($SEED)
      - pattern-not: $SEED = null
    message: "Using a deterministic seed with SecureRandom. Consider using a more secure seed."
    languages: [java]
    severity: WARNING
```

This rule will flag any instances in the code where `SecureRandom` is initialized with a specific seed, excluding cases where the seed is null (which implies a secure random seed).
OWASP Mobile Application Security Testing Guide: MASTG TECH 0039

---
title: Repackaging & Re-Signing
platform: android
---

## Repackaging

You can easily repackage an app by doing the following:

```bash
cd UnCrackable-Level1
apktool b
zipalign -v 4 dist/UnCrackable-Level1.apk ../UnCrackable-Repackaged.apk
```

Note that the Android Studio build tools directory must be in the path. It is located at `[SDK-Path]/build-tools/[version]`. The `zipalign` and `apksigner` tools are in this directory.

## Re-Signing

Before [re-signing](https://developer.android.com/studio/publish/app-signing), you first need a code-signing certificate. If you have built a project in Android Studio before, the IDE has already created a debug keystore and certificate in `$HOME/.android/debug.keystore`. The default password for this KeyStore is "android" and the key is called "androiddebugkey".

The standard Java distribution includes `keytool` for managing KeyStores and certificates. You can create your own signing certificate and key, then add it to the debug KeyStore:

```bash
keytool -genkey -v -keystore ~/.android/debug.keystore -alias signkey -keyalg RSA -keysize 2048 -validity 20000
```

After the certificate is available, you can re-sign the APK with it. Be sure that `apksigner` is in the path and that you run it from the folder where your repackaged APK is located.

```bash
apksigner sign --ks  ~/.android/debug.keystore --ks-key-alias signkey UnCrackable-Repackaged.apk
```

Note: If you experience JRE compatibility issues with `apksigner`, you can use `jarsigner` instead. When you do this, `zipalign` must be called **after** signing.

```bash
jarsigner -verbose -keystore ~/.android/debug.keystore ../UnCrackable-Repackaged.apk signkey
zipalign -v 4 dist/UnCrackable-Level1.apk ../UnCrackable-Repackaged.apk
```

Now you may reinstall the app:

```bash
adb install UnCrackable-Repackaged.apk
```
OWASP Mobile Application Security Testing Guide: MASTG TECH 0019

---
title: Retrieving Strings
platform: android
---

While performing any kind of binary analysis, strings can be considered as one of the most valuable starting points, as they provide context. For example, an error log string like "Data encryption failed." gives us a hint that the adjoining code might be responsible for performing some kind of encryption operation.

## Java and Kotlin Bytecode

As we already know, all the Java and Kotlin bytecode of an Android application is compiled into a DEX file. Each DEX file contains a [list of string identifiers](https://source.android.com/devices/tech/dalvik/dex-format#file-layout "string identifiers list") (strings_ids), which contains all the string identifiers used in the binary whenever a string is referred, including internal naming (e.g, type descriptors) or constant objects referred by the code (e.g hardcoded strings). You can simply dump this list using tools such as Ghidra (GUI-based) or [Dextra](http://www.newandroidbook.com/tools/dextra.html "Dextra") (CLI-based).

With Ghidra, strings can be obtained by simply loading the DEX file and selecting **Window -> Defined strings** in the menu.

> Loading an APK file directly into Ghidra might lead to inconsistencies. Thus, it is recommended to extract the DEX file by unzipping the APK file and then loading it into Ghidra.

<img src="Images/Chapters/0x05c/ghidra_dex_strings.png" width="100%" />

With Dextra, you can dump all the strings using the following command:

```bash
dextra -S classes.dex
```

The output from Dextra can be manipulated using standard Linux commands, for example, using `grep` to search for certain keywords.

It is important to know that the list of strings obtained using the above tools can be very big, as it also includes the various class and package names used in the application. Going through the complete list, especially for big binaries, can be very cumbersome. Thus, it is recommended to start with keyword-based searching and go through the list only when the keyword search does not help. Some generic keywords that can be a good starting point are - password, key, and secret. Other useful keywords specific to the context of the app can be obtained while you are using the app itself. For instance, imagine that the app has a login form, you can take note of the displayed placeholder or title text of the input fields and use that as an entry point for your static analysis.

## Native Code

In order to extract strings from native code used in an Android application, you can use GUI tools such as Ghidra or [iaito](https://github.com/radareorg/iaito "iaito") or rely on CLI-based tools such as the _strings_ Unix utility (`strings <path_to_binary>`) or radare2's @MASTG-TOOL-0129 (`rabin2 -zz <path_to_binary>`). When using the CLI-based ones, you can take advantage of other tools such as grep (e.g. in conjunction with regular expressions) to further filter and analyze the results.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0033

---
title: Method Tracing
platform: android
---

In contrast to method profiling, which tells you how frequently a method is being called, method tracing helps you determine its input and output values. This technique can prove to be very useful when dealing with applications that have a big codebase and/or are obfuscated.

If you prefer a GUI-based approach, you can use tools such as @MASTG-TOOL-0037, which enables a more visual experience as well as includes several convenience [tracing options](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security#3-hook-on-the-fly-classesmethods-and-trace-their-args-and-return-values).

If you prefer the command line, Frida offers a useful syntax to query Java classes and methods as well as Java method tracing support for frida-trace via `-j` (starting on frida-tools 8.0, Frida 12.10).

- In Frida scripts: e.g. `Java.enumerateMethods('*youtube*!on*')` uses globs to take all classes that include "youtube" as part of their name and enumerate all methods starting with "on".
- In frida-trace: e.g. `-j '*!*certificate*/isu'` triggers a case-insensitive query (`i`), including method signatures (`s`) and excluding system classes (`u`).

Refer to the [Release Notes for Frida 12.10](https://frida.re/news/2020/06/29/frida-12-10-released/ "Frida 12.10") for more details on this new feature. To learn more about all options for advanced usage, check the [documentation on the official Frida website](https://frida.re/docs/frida-trace/ "documentation").