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

---
title: Obtaining Information from the AndroidManifest
platform: android
---

The [AndroidManifest.xml](../../Document/0x05a-Platform-Overview.md) file is a critical component of any Android application, providing essential information about the app's structure, permissions, components, and configurations. During a security assessment, analyzing the manifest can reveal potential vulnerabilities or misconfigurations that could be exploited by attackers.

The AndroidManifest is stored in a binary XML format and cannot simply be extracted from the APK by unzipping it. To properly analyze the manifest, you first need to extract and decode it into a human-readable XML format.

Different tools extract the manifest in various formats, with some preserving more raw structure while others interpret or modify it during decoding.

## Using @MASTG-TOOL-0018

Use jadx CLI with `--no-src` to extract only resources without decompiling all sources:

```sh
jadx --no-src -d out_dir MASTG-DEMO-0001.apk
```

jadx outputs the manifest in full to `out_dir/resources/AndroidManifest.xml`, including the `<uses-sdk>` element, which is not included when using other tools like apktool.

```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>
    <uses-sdk
        android:minSdkVersion="29"
        android:targetSdkVersion="35" />
```

## Using @MASTG-TOOL-0011

The AndroidManifest can be extracted using apktool:

```sh
$ apktool d -s -f -o output_dir MASTG-DEMO-0001.apk
I: Using Apktool 2.11.1 on MASTG-DEMO-0001.apk with 8 threads
I: Copying raw classes.dex file...
...
I: Loading resource table...
I: Decoding file-resources...
I: Decoding values */* XMLs...
I: Decoding AndroidManifest.xml with resources...
```

`-s` skips baksmaliing the dex files and is faster.

The AndroidManifest.xml is extracted and decoded to `output_dir/AndroidManifest.xml`, where you can simply open and view it.

When you decode an APK with apktool, you might notice that the `<uses‑sdk>` element (which includes `minSdkVersion` and `targetSdkVersion`) is missing from the decompiled AndroidManifest.xml. That's expected behavior.

Apktool moves those values into a separate file called apktool.yml rather than inserting them into the decoded XML manifest. In that file, you'll see something like:

```yml
sdkInfo:
  minSdkVersion: 29
  targetSdkVersion: 35
```

## Using @MASTG-TOOL-0124

If you are only interested in specific values of the manifest, you can use aapt2.

Note that **the output is not an XML file**.

```bash
$ aapt2 d badging MASTG-DEMO-0001.apk
package: name='org.owasp.mastestapp' versionCode='1' versionName='1.0' platformBuildVersionName='15' platformBuildVersionCode='35' compileSdkVersion='35' compileSdkVersionCodename='15'
sdkVersion:'29'
targetSdkVersion:'35'
uses-permission: name='android.permission.INTERNET'
uses-permission: name='org.owasp.mastestapp.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION'
application-label:'MASTestApp'
...
```
OWASP Mobile Application Security Testing Guide: MASTG TECH 0148

---
title: Interacting with Android ContentProviders
platform: android
---

See @MASTG-KNOW-0117 for an overview of Android `ContentProvider`s, including URI structure, access control, and query handling.

## Using @MASTG-TOOL-0004

You can use @MASTG-TOOL-0004 to interact with `ContentProvider`s on a device or emulator via the `content` command.

### Query rows

```bash
adb shell content query --uri content://org.owasp.mastestapp.provider/students
adb shell content query --uri content://org.owasp.mastestapp.provider/students --where "name='Bob'"
```

### Insert a row

```bash
adb shell content insert \
    --uri content://org.owasp.mastestapp.provider/students \
    --bind name:s:Eve
```

### Update rows

```bash
adb shell content update \
    --uri content://org.owasp.mastestapp.provider/students \
    --where "id=1" \
    --bind name:s:"Alice Jr"
```

### Delete rows

```bash
adb shell content delete \
    --uri content://org.owasp.mastestapp.provider/students \
    --where "id=3"
```

## Notes

- The `--where` argument maps directly to the `selection` parameter in `ContentProvider.query()`.
- The command executes in the context of the shell user, so access depends on whether the provider is exported and what permissions are enforced.
- Quoting and escaping are important when passing strings or crafting test inputs, especially when using SQL operators.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0004

---
title: Repackaging Apps
platform: android
---

If you need to test on a non-jailbroken device, you should learn how to repackage an app to enable dynamic testing on it.

Use a computer to perform all the steps indicated in the article ["Patching Android Applications"](https://github.com/sensepost/objection/wiki/Patching-Android-Applications) from the objection Wiki. Once you're done, you'll be able to patch an APK by calling the objection command:

```bash
objection patchapk --source app-release.apk
```

The patched application then needs to be installed using @MASTG-TOOL-0004.

> This repackaging method is enough for most use cases. For more advanced repackaging, refer to @MASTG-TECH-0039.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0021

---
title: Information Gathering - API Usage
platform: android
---

The Android platform provides many built-in libraries for frequently used functionalities in applications, for example, cryptography, Bluetooth, NFC, network, or location libraries. Determining the presence of these libraries in an application can give us valuable information about its nature.

For instance, if an application is importing `javax.crypto.Cipher`, it indicates that the application will be performing some kind of cryptographic operation. Fortunately, cryptographic calls are very standard in nature, i.e, they need to be called in a particular order to work correctly. This knowledge can be helpful when analyzing cryptography APIs. For example, by looking for the `Cipher.getInstance` function, we can determine the cryptographic algorithm being used. With such an approach, we can directly move to analyzing cryptographic assets, which are often very critical in an application. Further information on how to analyze Android's cryptographic APIs is discussed in the section "[Android Cryptographic APIs](../../Document/0x05e-Testing-Cryptography.md "Android Cryptographic APIs")".

Similarly, the above approach can be used to determine where and how an application is using NFC. For instance, an application using Host-based Card Emulation for performing digital payments must use the `android.nfc` package. Therefore, a good starting point for NFC API analysis would be to consult the [Android Developer Documentation](https://developer.android.com/guide/topics/connectivity/nfc/hce "Host-based card emulation overview") to get some ideas and start searching for critical functions such as `processCommandApdu` from the `android.nfc.cardemulation.HostApduService` class.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0006

---
title: Listing Installed Apps
platform: android
---

When targeting apps that are installed on the device, you'll first have to figure out the correct package name of the application you want to analyze. You can retrieve the installed apps either by using `pm` (Android Package Manager) or by using `frida-ps`:

```bash
$ adb shell pm list packages
package:sg.vantagepoint.helloworldjni
package:eu.chainfire.supersu
package:org.teamsik.apps.hackingchallenge.easy
package:org.teamsik.apps.hackingchallenge.hard
package:sg.vp.owasp_mobile.omtg_android
```

You can include flags to show only third-party apps (`-3`) and the location of their APK file (`-f`), which you can use afterwards to download it via `adb pull`:

```bash
$ adb shell pm list packages -3 -f
package:/data/app/sg.vantagepoint.helloworldjni-1/base.apk=sg.vantagepoint.helloworldjni
package:/data/app/eu.chainfire.supersu-1/base.apk=eu.chainfire.supersu
package:/data/app/org.teamsik.apps.hackingchallenge.easy-1/base.apk=org.teamsik.apps.hackingchallenge.easy
package:/data/app/org.teamsik.apps.hackingchallenge.hard-1/base.apk=org.teamsik.apps.hackingchallenge.hard
package:/data/app/sg.vp.owasp_mobile.omtg_android-kR0ovWl9eoU_yh0jPJ9caQ==/base.apk=sg.vp.owasp_mobile.omtg_android
```

This is the same as running `adb shell pm path <app_package_id>` on an app package ID:

```bash
$ adb shell pm path sg.vp.owasp_mobile.omtg_android
package:/data/app/sg.vp.owasp_mobile.omtg_android-kR0ovWl9eoU_yh0jPJ9caQ==/base.apk
```

Use `frida-ps -Uai` to get all apps (`-a`) currently installed (`-i`) on the connected USB device (`-U`):

```bash
$ frida-ps -Uai
  PID  Name                                      Identifier
-----  ----------------------------------------  ---------------------------------------
  766  Android System                            android
21228  Attack me if u can                        sg.vp.owasp_mobile.omtg_android
 4281  Termux                                    com.termux
    -  Uncrackable1                              sg.vantagepoint.uncrackable1
```

Note that this also shows the PID of the apps that are running at the moment. Take a note of the "Identifier" and the PID, if any, as you'll need them afterwards.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0141

---
title: Inspecting the Merged AndroidManifest
platform: android
---

During the build process, the Android build tools merge multiple manifest files from different sources (main app, flavors, and libraries) into a single merged manifest file. This merged manifest file is what gets packaged into the final APK or AAB.

Inspecting the merged manifest file can help you understand the final configuration of the app, including permissions, components (i.e, Activities, Services, Providers), and other settings. It can also help you identify the inherited permissions and components from third-party libraries.

## Using @MASTG-TOOL-0007

1. Open your project in Android Studio.
2. In the Project view, navigate to `app/src/main/AndroidManifest.xml`.
3. Click on the "Merged Manifest" tab at the bottom of the editor window. This will show you the merged manifest file, along with a tree view of the sources that contributed to each element.
4. You can click on any element, such as a permission or an Activity, in the merged manifest to see its source in the tree view.

## Using Command-Line Tools

!!! warning Limitation
    With this method, you cannot track the source of each element in the merged manifest file. For this, you will need to use Android Studio, as described [above](#using-mastg-tool-0007).

1. You can manually generate the merged manifest file of the desired build variant using a command like `./gradlew app:processDebugManifest`. Replace `Debug` with the desired build variant if necessary.
2. After running the command, you can find the merged manifest file in the `app/build/intermediates/merged_manifests/debug/AndroidManifest.xml` directory. Again, replace `debug` with the appropriate build variant if needed.
3. Open the `AndroidManifest.xml` file in a text editor to inspect its contents.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0009

---
title: Monitoring System Logs
platform: android
---

On Android, you can easily inspect the log of system messages by using [`Logcat`](https://developer.android.com/tools/debugging/debugging-log.html "Debugging with Logcat"). There are two ways to execute Logcat:

- In Android Studio, if the app is running in debug mode, the log output will be shown in the **Logcat** window (accessible via **View** -> **Tool Windows** -> **Logcat**). You can filter the app's log output by defining patterns in Logcat.

<img src="Images/Chapters/0x05b/log_output_Android_Studio.png" width="100%" />

- You can execute Logcat with @MASTG-TOOL-0004 to store the log output permanently:

```bash
adb logcat > logcat.log
```

With the following command, you can specifically grep for the log output of the app in scope, just insert the package name. Of course, your app needs to be running for `ps` to be able to get its PID.

```bash
adb logcat | grep "$(adb shell ps | grep <package-name> | awk '{print $2}')"
```

If you already know the app PID, you may give it directly using `--pid` flag.

You may also want to apply further filters or regular expressions (using `logcat`'s regex flags `-e <expr>, --regex=<expr>` for example) if you expect certain strings or patterns to come up in the logs.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0035

---
title: JNI Tracing
platform: android
---

As detailed in @MASTG-TECH-0024, the first argument passed to every JNI function is a JNI interface pointer. This pointer contains a table of functions that allows native code to access the Android Runtime. Identifying calls to these functions can help with understanding library functionality, such as what strings are created or Java methods are called.

[jnitrace](https://github.com/chame1eon/jnitrace "jnitrace") is a Frida-based tool similar to frida-trace, which specifically targets the usage of Android's JNI API by native libraries, providing a convenient way to obtain JNI method traces, including arguments and return values.

You can easily install it by running `pip install jnitrace` and running it straight away as follows:

```bash
jnitrace -l libnative-lib.so sg.vantagepoint.helloworldjni
```

> The `-l` option can be provided multiple times to trace multiple libraries, or `*` can be provided to trace all libraries. This, however, may provide a lot of output.

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

In the output, you can see the trace of a call to `NewStringUTF` made from the native code (its return value is then given back to Java code, see @MASTG-TECH-0024 for more details). Note how, similarly to frida-trace, the output is colorized, helping to visually distinguish the different threads.

When tracing JNI API calls, you can see the thread ID at the top, followed by the JNI method call, including the method name, the input arguments, and the return value. In the case of a call to a Java method from native code, the Java method arguments will also be supplied. Finally, jnitrace will attempt to use the Frida backtracing library to show where the JNI call was made from.

To learn more about all options for advanced usage, check the [documentation on the jnitrace GitHub page](https://github.com/chame1eon/jnitrace "documentation").
OWASP Mobile Application Security Testing Guide: MASTG TECH 0142

---
title: Inspecting WebView Storage
platform: android
---

To inspect WebView Storage, first follow the steps in official ["Remote debugging WebViews" documentation](https://developer.chrome.com/docs/devtools/remote-debugging/webviews) to connect Chrome DevTools to the WebView of your app.

With the DevTools open, navigate to the Application tab. In the Storage section, you can inspect the different storage areas of the WebView.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0128

---
title: Performing a Backup and Restore of App Data
platform: android 
---

## Using the Backup Manager (via @MASTG-TOOL-0004 shell)

Run [Backup Manager (`adb shell bmgr`)](https://developer.android.com/identity/data/testingbackup#TestingBackup)

{{ ../../utils/mastg-android-backup-bmgr.sh }}

When using the cloud transport variant, each app's backup is managed and stored independently in the user's Google Drive. In our case, we're interested in the local transport variant, where `bmgr` stores each app's backup data in a separate `.ab` file within the `/data/data/com.android.localtransport/files/` directory on the device. To extract the file, run:

```sh
adb root
adb pull /data/data/com.android.localtransport/files/1/_full/org.owasp.mastestapp org.owasp.mastestapp.ab
tar xvf org.owasp.mastestapp.ab
```

The extracted backup directory (`apps/`) is stored in the current working directory. For instructions on how to inspect it, see @MASTG-TECH-0127.

## Using @MASTG-TOOL-0004 Backup

!!! warning
    `adb backup` is [restricted since Android 12](https://developer.android.com/about/versions/12/behavior-changes-12#adb-backup-restrictions) and requires `android:debuggable=true` in the AndroidManifest.xml.

You can run `adb backup` to back up the app data. Approve the backup from your device by selecting the _Back up my data_ option. After the backup process is finished, the file _.ab_ will be in your working directory.

{{ ../../utils/mastg-android-backup-adb.sh }}

The extracted backup directory (`apps/`) is stored in the current working directory. For instructions on how to inspect it, see @MASTG-TECH-0127.

**Note:** The behavior might differ between an emulator and a physical device.

## Using Android Backup Extractor

You can use [Android Backup Extractor](https://github.com/nelenkov/android-backup-extractor) to extract the backup data. For more information, refer to its GitHub repo.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0013

---
title: Reverse Engineering Android Apps
platform: android
---

Android's openness makes it a favorable environment for reverse engineers, offering big advantages that are not available with iOS. Because Android is open-source, you can study its source code at the Android Open Source Project (AOSP) and modify the OS and its standard tools any way you want. Even on standard retail devices, it is possible to do things like activating developer mode and sideloading apps without jumping through many hoops. From the powerful tools shipping with the SDK to the wide range of available reverse engineering tools, there are a lot of niceties to make your life easier.

However, there are also a few Android-specific challenges. For example, you'll need to deal with both Java bytecode and native code. Java Native Interface (JNI) is sometimes deliberately used to confuse reverse engineers (to be fair, there are legitimate reasons for using JNI, such as improving performance or supporting legacy code). Developers sometimes use the native layer to "hide" data and functionality, and they may structure their apps such that execution frequently jumps between the two layers.

You'll need at least a working knowledge of both the Java-based Android environment and the Linux OS and Kernel, on which Android is based. You'll also need the right toolset to deal with both the bytecode running on the Java virtual machine and the native code.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0027

---
title: Get Open Files
platform: android
---

You can use `lsof` with the flag `-p <pid>` to return the list of open files for the specified process. See the [man page](http://man7.org/linux/man-pages/man8/lsof.8.html "Man Page of lsof") for more options.

```bash
# lsof -p 6233
COMMAND     PID       USER   FD      TYPE             DEVICE  SIZE/OFF       NODE NAME
.foobar.c  6233     u0_a97  cwd       DIR                0,1         0          1 /
.foobar.c  6233     u0_a97  rtd       DIR                0,1         0          1 /
.foobar.c  6233     u0_a97  txt       REG             259,11     23968        399 /system/bin/app_process64
.foobar.c  6233     u0_a97  mem   unknown                                         /dev/ashmem/dalvik-main space (region space) (deleted)
.foobar.c  6233     u0_a97  mem       REG              253,0   2797568    1146914 /data/dalvik-cache/arm64/system@framework@boot.art
.foobar.c  6233     u0_a97  mem       REG              253,0   1081344    1146915 /data/dalvik-cache/arm64/system@framework@boot-core-libart.art
...
```

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

- `NAME`: path of the file.
- `TYPE`: type of the file, for example, whether the file is a directory or a regular file.

This can be extremely useful to spot unusual files when monitoring applications using obfuscation or other anti-reverse engineering techniques, without having to reverse the code. For instance, an application might be performing encryption-decryption of data and storing it in a file temporarily.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0036

---
title: Emulation-based Analysis
platform: android
---

The Android emulator is based on QEMU, a generic and open source machine emulator. QEMU emulates a guest CPU by translating the guest instructions on-the-fly into instructions the host processor can understand. Each basic block of guest instructions is disassembled and translated into an intermediate representation called Tiny Code Generator (TCG). The TCG block is compiled into a block of host instructions, stored in a code cache, and executed. After execution of the basic block, QEMU repeats the process for the next block of guest instructions (or loads the already translated block from the cache). The whole process is called dynamic binary translation.

Because the Android emulator is a fork of QEMU, it comes with all QEMU features, including monitoring, debugging, and tracing facilities. QEMU-specific parameters can be passed to the emulator with the `-qemu` command line flag. You can use QEMU's built-in tracing facilities to log executed instructions and virtual register values. Starting QEMU with the `-d` command line flag will cause it to dump the blocks of guest code, micro operations, or host instructions being executed. With the `-d_asm` flag, QEMU logs all basic blocks of guest code as they enter QEMU's translation function. The following command logs all translated blocks to a file:

```bash
emulator -show-kernel -avd Nexus_4_API_19 -snapshot default-boot -no-snapshot-save -qemu -d in_asm,cpu 2>/tmp/qemu.log
```

Unfortunately, generating a complete guest instruction trace with QEMU is impossible because code blocks are written to the log only at the time they are translated, not when they're taken from the cache. For example, if a block is repeatedly executed in a loop, only the first iteration will be printed to the log. There's no way to disable TB caching in QEMU (besides hacking the source code). Nevertheless, the functionality is sufficient for basic tasks, such as reconstructing the disassembly of a natively executed cryptographic algorithm.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0029

---
title: Get Loaded Native Libraries
platform: android
---

## Using Process Memory Maps

The file `/proc/<pid>/maps` contains the currently mapped memory regions and their access permissions. Using this file, we can get the list of the libraries loaded in the process.

```bash
# cat /proc/9568/maps
12c00000-52c00000 rw-p 00000000 00:04 14917                              /dev/ashmem/dalvik-main space (region space) (deleted)
6f019000-6f2c0000 rw-p 00000000 fd:00 1146914                            /data/dalvik-cache/arm64/system@framework@boot.art
...[PII_REDACTED][PII_REDACTED] r--p 00000000 fd:00 1884627                        /data/app/com.google.android.gms-4FJbDh-oZv-5bCw39jkIMQ==/oat/arm64/base.odex
..
733494d000-7334cfb000 r-xp 00000000 fd:00 1884542                        /data/app/com.google.android.youtube-Rl_hl9LptFQf3Vf-JJReGw==/lib/arm64/libcronet.80.0.3970.3.so
...
```

## Using Frida

You can retrieve process-related information straight from the Frida CLI by using the `Process` command. Within the `Process` command, the function `enumerateModules` lists the libraries loaded into the process memory.

```bash
[Huawei Nexus 6P::sg.vantagepoint.helloworldjni]-> Process.enumerateModules()
[
    {
        "base": "0x558a442000",
        "name": "app_process64",
        "path": "/system/bin/app_process64",
        "size": 32768
    },
    {
        "base": "0x78bc984000",
        "name": "libandroid_runtime.so",
        "path": "/system/lib64/libandroid_runtime.so",
        "size": 2011136
    },
...

```