Translated ['', 'src/mobile-pentesting/android-app-pentesting/README.md'

This commit is contained in:
Translator 2025-09-08 01:55:51 +00:00
parent 79ad7d5d05
commit 65ebdc25a6
5 changed files with 605 additions and 400 deletions

View File

@ -1,10 +1,10 @@
# Android Applications Pentesting # Android アプリケーション Pentesting
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Androidアプリケーションの基本 ## Android アプリケーションの基礎
このページをまず読むことを強くお勧めします。**Androidのセキュリティに関連する最も重要な部分と、Androidアプリケーション内で最も危険なコンポーネント**について知ることができます このページを最初に読むことを強く推奨します。**Android のセキュリティに関連する最も重要な部分と、Android アプリケーション内で最も危険なコンポーネント**について知ることができます:
{{#ref}} {{#ref}}
@ -13,24 +13,24 @@ android-applications-basics.md
## ADB (Android Debug Bridge) ## ADB (Android Debug Bridge)
これは、androidデバイスエミュレートされたものまたは実機に接続するための主要なツールです。\ これは、エミュレートまたは実機の Android デバイスに接続するための主要なツールです。\
**ADB**を使うと、コンピュータから**USB**または**Network**経由でデバイスを制御できます。このユーティリティは、双方向のファイルの**コピー**、アプリの**インストール**と**アンインストール**、シェルコマンドの**実行**、データの**バックアップ**、ログの**読み取り**などの機能を提供します。 **ADB** を使用すると、コンピュータから **USB** または **Network** 経由でデバイスを制御できます。このユーティリティは、ファイルの双方向の **copying**、アプリの **installation****uninstallation**、シェルコマンドの **execution**、データの **backing up**、ログの **reading** などの機能を提供します。
次の[**ADB Commands**](adb-commands.md)の一覧を参照してadbの使い方を学んでください。 adb の使い方を学ぶには、次の [**ADB Commands**](adb-commands.md) を参照してください。
## Smali ## Smali
場合によっては、**隠された情報**(難読化されたパスワードやフラグなど)にアクセスするために**アプリケーションのコードを変更する**ことが有用です。そこで、apkを逆コンパイルしてコードを修正し、再コンパイルすることが有効な場合があります。\ 場合によっては、**modify the application code** して **hidden information**(難読化されたパスワードや flags などにアクセスすることが有益です。そのため、apk を逆コンパイルしてコードを修正し、再コンパイルすることが有効な場合があります。\
[**In this tutorial** you can **learn how to decompile and APK, modify Smali code and recompile the APK** with the new functionality](smali-changes.md)。これは、これから紹介する動的解析中の複数のテストの**代替手段として非常に有用**です。したがって、**常にこの可能性を念頭に置いてください** [**In this tutorial** you can **learn how to decompile and APK, modify Smali code and recompile the APK** with the new functionality](smali-changes.md)。この手法は、これから示す**dynamic analysis**中のいくつかのテストの代替手段として非常に有用です。したがって、この可能性を常に念頭に置いてください
## その他の興味深いトリック ## Other interesting tricks
- [Spoofing your location in Play Store](spoofing-your-location-in-play-store.md) - [Spoofing your location in Play Store](spoofing-your-location-in-play-store.md)
- [Shizuku Privileged API (ADB-based non-root privileged access)](shizuku-privileged-api.md) - [Shizuku Privileged API (ADB-based non-root privileged access)](shizuku-privileged-api.md)
- [Exploiting Insecure In-App Update Mechanisms](insecure-in-app-update-rce.md) - [Exploiting Insecure In-App Update Mechanisms](insecure-in-app-update-rce.md)
- [Abusing Accessibility Services (Android RAT)](accessibility-services-abuse.md) - [Abusing Accessibility Services (Android RAT)](accessibility-services-abuse.md)
- **APKのダウンロード**: [https://apps.evozi.com/apk-downloader/](https://apps.evozi.com/apk-downloader/), [https://apkpure.com/es/](https://apkpure.com/es/), [https://www.apkmirror.com/](https://www.apkmirror.com), [https://apkcombo.com/es-es/apk-downloader/](https://apkcombo.com/es-es/apk-downloader/), [https://github.com/kiber-io/apkd](https://github.com/kiber-io/apkd) - **Download APKs**: [https://apps.evozi.com/apk-downloader/](https://apps.evozi.com/apk-downloader/), [https://apkpure.com/es/](https://apkpure.com/es/), [https://www.apkmirror.com/](https://www.apkmirror.com), [https://apkcombo.com/es-es/apk-downloader/](https://apkcombo.com/es-es/apk-downloader/), [https://github.com/kiber-io/apkd](https://github.com/kiber-io/apkd)
- デバイスからAPKを抽出: - デバイスから APK を抽出する方法:
```bash ```bash
adb shell pm list packages adb shell pm list packages
com.android.insecurebankv2 com.android.insecurebankv2
@ -40,7 +40,7 @@ package:/data/app/com.android.insecurebankv2-Jnf8pNgwy3QA_U5f-n_4jQ==/base.apk
adb pull /data/app/com.android.insecurebankv2-Jnf8pNgwy3QA_U5f-n_4jQ==/base.apk adb pull /data/app/com.android.insecurebankv2-Jnf8pNgwy3QA_U5f-n_4jQ==/base.apk
``` ```
- すべての splits と base apks を [APKEditor](https://github.com/REAndroid/APKEditor) マージする: - [APKEditor](https://github.com/REAndroid/APKEditor) を使って、すべての splits と base apks をマージする:
```bash ```bash
mkdir splits mkdir splits
adb shell pm path com.android.insecurebankv2 | cut -d ':' -f 2 | xargs -n1 -i adb pull {} splits adb shell pm path com.android.insecurebankv2 | cut -d ':' -f 2 | xargs -n1 -i adb pull {} splits
@ -49,7 +49,7 @@ java -jar ../APKEditor.jar m -i splits/ -o merged.apk
# after merging, you will need to align and sign the apk, personally, I like to use the uberapksigner # after merging, you will need to align and sign the apk, personally, I like to use the uberapksigner
java -jar uber-apk-signer.jar -a merged.apk --allowResign -o merged_signed java -jar uber-apk-signer.jar -a merged.apk --allowResign -o merged_signed
``` ```
## ケーススタディ & 脆弱性 ## ケーススタディ脆弱性
{{#ref}} {{#ref}}
@ -61,39 +61,38 @@ java -jar uber-apk-signer.jar -a merged.apk --allowResign -o merged_signed
../../linux-hardening/privilege-escalation/android-rooting-frameworks-manager-auth-bypass-syscall-hook.md ../../linux-hardening/privilege-escalation/android-rooting-frameworks-manager-auth-bypass-syscall-hook.md
{{#endref}} {{#endref}}
## 静的解析 ## Static Analysis
まず、APK を解析する際は decompiler を使って **Java コードを確認する**べきです。\ まず、APKを解析するには、decompilerを使って**Java code**を確認してください。\
Please, [**read here to find information about different available decompilers**](apk-decompilers.md). Please, [**read here to find information about different available decompilers**](apk-decompilers.md).
### 興味深い情報を探す ### Looking for interesting Info
APK**strings** を見るだけで、**passwords**、**URLs** ([https://github.com/ndelphit/apkurlgrep](https://github.com/ndelphit/apkurlgrep))、**api** keys、**encryption**、**bluetooth uuids**、**tokens** など興味深いものを探せます。コード実行の **backdoors** や認証 backdoorsアプリにハードコードされた管理者資格情報も確認してください APKの**strings**を確認するだけで、**passwords**、**URLs** ([https://github.com/ndelphit/apkurlgrep](https://github.com/ndelphit/apkurlgrep))、**api** keys、**encryption**、**bluetooth uuids**、**tokens**などの有用な情報を探せます。コード実行の**backdoors**や認証バックドア(アプリにハードコードされた管理者資格情報)なども見つかることがあります
**Firebase** **Firebase**
**Firebase** の URL に特に注意し、設定が不適切でないか確認してください。[More information about whats is FIrebase and how to exploit it here.](../../network-services-pentesting/pentesting-web/buckets/firebase-database.md) Firebase に特に注意して、**firebase URLs** が誤設定されていないか確認してください。 [More information about whats is FIrebase and how to exploit it here.](../../network-services-pentesting/pentesting-web/buckets/firebase-database.md)
### アプリケーションの基本的理解 - Manifest.xml, strings.xml ### Basic understanding of the application - Manifest.xml, strings.xml
アプリケーションの _Manifest.xml_ **_strings.xml_** を調査することで、潜在的なセキュリティ脆弱性を明らかにできることがあります。これらのファイルは decompiler を使うか、APK の拡張子を .zip に変更して展開することで参照できます。 アプリケーションの _Manifest.xml_ および _strings.xml_ ファイルを**調査することで潜在的なセキュリティ脆弱性が明らかになることがあります**。これらのファイルは decompiler を使うか、APK の拡張子を .zip に変更して解凍することで取得できます。
**Manifest.xml** から特定できる **脆弱性** には以下が含まれます: **Manifest.xml** から識別される脆弱性には以下があります:
- **Debuggable Applications**: _Manifest.xml_ `debuggable="true"` に設定されたアプリは、接続を許可してしまい、悪用のリスクがあります。デバッグ可能なアプリをデバイス上で検出して悪用する方法については、該当チュートリアルを参照してください。 - **Debuggable Applications**: _Manifest.xml_ 内で debuggable (`debuggable="true"`) に設定されたアプリケーションは、接続を許可し悪用につながる可能性があるためリスクがあります。デバッグ可能なアプリを発見して悪用する方法については、デバイス上でのデバッグ可能アプリの検出と悪用に関するチュートリアルを参照してください。
- **Backup Settings**: 敏感な情報を扱うアプリでは、`android:allowBackup="false"` を明示的に設定しておくべきです。特に USB debugging が有効な場合、adb 経由での不正なデータバックアップを防ぐためです - **Backup Settings**: 機密情報を扱うアプリでは、adb 経由での不正なデータバックアップを防ぐために `android:allowBackup="false"` を明示的に設定するべきです(特に USB デバッグが有効な場合)
- **Network Security**: `android:networkSecurityConfig="@xml/network_security_config"` のようなカスタム network security 設定(`res/xml/`は、certificate pinning や HTTP トラフィック設定などのセキュリティ詳細を指定できます。例として特定ドメインで HTTP トラフィックを許可しているケースなどがあります。 - **Network Security**: _res/xml/_ 内のカスタム network security 設定(`android:networkSecurityConfig="@xml/network_security_config"`)は、証明書ピンや HTTP トラフィック許可などのセキュリティ詳細を指定できます。特定ドメインに対して HTTP トラフィックを許可する例などが考えられます。
- **Exported Activities and Services**: マニフェストで exported な activities や services を特定すると、悪用されうるコンポーネントが浮き彫りになります。動的テストでこれらをさらに解析し、どのように悪用できるかを確認します - **Exported Activities and Services**: マニフェストにエクスポートされた activity や service を特定することで、悪用されうるコンポーネントを浮き彫りにできます。動的テスト時にさらに解析して、それらがどのように悪用され得るかを確認してください
- **Content Providers and FileProviders**: 公開されている content provider はデータの不正アクセスや改竄を許す可能性があります。FileProviders の設定も注意深く確認してください。 - **Content Providers and FileProviders**: 公開された content provider はデータへの不正アクセスや改ざんを許す可能性があります。FileProvider の設定も入念に確認してください。
- **Broadcast Receivers and URL Schemes**: これらのコンポーネントは悪用される可能性があり、特に URL schemes の扱い方が入力に対する脆弱性を生まないかを確認する必要があります - **Broadcast Receivers and URL Schemes**: これらのコンポーネントは悪用に利用され得るため、特に URL スキームの扱いによる入力脆弱性に注意してください
- **SDK Versions**: `minSdkVersion``targetSDKVersion``maxSdkVersion` はサポートしている Android バージョンを示します。古い脆弱な Android バージョンをサポートしないことが重要です。 - **SDK Versions**: `minSdkVersion``targetSDKVersion``maxSdkVersion` の属性はサポートされる Android バージョンを示し、古い脆弱なバージョンをサポートしないことが重要です。
**strings.xml** ファイルからは、API keys、カスタムスキーマ、その他開発者のメモなどの機密情報が見つかることがあり、これらのリソースは注意深く確認する必要があります。 **strings.xml** ファイルからは、API keys、カスタムスキーマ、その他の開発者メモのような機密情報が発見されることがあり、これらのリソースは注意深く確認する必要があります。
### Tapjacking ### Tapjacking
**Tapjacking** は、**malicious** な **application** を起動して **victim application の上に重ねて配置する**攻撃です。victim app を視覚的に覆い隠した状態で、UI をユーザを騙すように設計し、ユーザの操作を victim app に渡すようにします。\ Tapjacking は、悪意のあるアプリケーションが起動して被害者アプリの上に自身を配置する攻撃です。視覚的に被害者アプリを覆い隠した状態で、UI がユーザをだまして操作させ、その操作を被害者アプリへ透過させるように設計されます。結果として、ユーザは実際には被害者アプリ上で操作を行っていることに気づかなくなります。
結果として、ユーザは実際には victim app 上で操作を行っていることに気づかされないまま操作させられてしまいます。
Find more information in: Find more information in:
@ -104,7 +103,7 @@ tapjacking.md
### Task Hijacking ### Task Hijacking
`launchMode`**`singleTask``taskAffinity` が定義されていない** activity は Task Hijacking の脆弱性があります。つまり、悪意ある **application** をインストールして、そのアプリが本来のアプリより先に起動されると、**本来のアプリのタスクをハイジャック**してしまう可能性があり(ユーザは本物のアプリを使っているつもりで悪意あるアプリを操作している)、危険です。 `launchMode`**`singleTask`** に設定され、かつ `taskAffinity` が定義されていない activity は Task Hijacking の対象になります。つまり、悪意あるアプリをインストールしてそのアプリを本物のアプリより先に起動すると、本物のアプリのタスクを**乗っ取る**ことができ(ユーザは本物のアプリを操作しているつもりで実は悪意あるアプリを操作している)、ユーザを騙すことができます。
More info in: More info in:
@ -117,97 +116,97 @@ android-task-hijacking.md
**Internal Storage** **Internal Storage**
Android では、**internal** ストレージに保存されたファイルは、それを作成した **app** のみがアクセスできるように設計されています。このセキュリティ対策は OS によって強制されており、多くのアプリのセキュリティ要件には十分です。しかし、開発者が `MODE_WORLD_READABLE``MODE_WORLD_WRITABLE` のようなモードを使用して複数のアプリ間でファイルを共有する場合があります。これらのモードは他のアプリ、場合によっては悪意あるアプリからのアクセスを制限しません。 Android では、internal storage に保存されたファイルはそれを作成したアプリのみがアクセスできるよう設計されています。これは OS によって強制され、多くのアプリケーションにとって十分なセキュリティ手段です。しかし、開発者が `MODE_WORLD_READABLE``MODE_WORLD_WRITABLE` といったモードを利用してファイルを他のアプリ間で共有することがあり、これらのモードは他の(悪意ある可能性のある)アプリからのアクセスを制限しません。
1. **Static Analysis:** 1. **Static Analysis:**
- `MODE_WORLD_READABLE` `MODE_WORLD_WRITABLE` の使用がないかを慎重に確認してください。これらのモードはファイルを意図しない、または不正なアクセスに晒す可能性があります。 - `MODE_WORLD_READABLE` `MODE_WORLD_WRITABLE` の使用を慎重に調査してください。これらのモードはファイルを意図しない、または許可されていないアクセスにさらす可能性があります。
2. **Dynamic Analysis:** 2. **Dynamic Analysis:**
- アプリが作成するファイルの権限を確認してください。特に、ファイルが worldwide に読み取り可能または書き込み可能に設定されていないかをチェックします。これが有効だと、デバイスにインストールされている任意のアプリがこれらのファイルを読み書きできるため、重大なセキュリティリスクになります。 - アプリが作成するファイルに設定されている権限を確認してください。特に、ファイルが全世界で読み取り可能または書き込み可能に設定されていないかをチェックしてください。これがあると、デバイスにインストールされた任意のアプリケーションが当該ファイルを読み取ったり変更したりできる重大なリスクになります。
**External Storage** **External Storage**
SD カードなどの **external storage** 上のファイルを扱う際は、以下の点に注意してください: SD カードなどの external storage 上のファイルを扱う場合は、以下の点に注意してください:
1. **Accessibility**: 1. **Accessibility**:
- external storage 上のファイルは一般的にグローバルに読み書き可能です。つまり任意のアプリやユーザがアクセスできます。 - external storage 上のファイルはグローバルに読み書き可能です。つまり任意のアプリケーションやユーザがアクセスできます。
2. **Security Concerns**: 2. **Security Concerns**:
- アクセスが容易ため、機密情報を external storage に保存しないことが推奨されます。 - アクセスが容易であるため、機密情報を external storage に保存しないことが推奨されます。
- external storage は取り外し可能であり、任意のアプリからアクセスされる可能性があるため、安全性が低くなります。 - external storage は取り外し可能であり、任意のアプリケーションからアクセスされ得るため安全性は低くなります。
3. **Handling Data from External Storage**: 3. **Handling Data from External Storage**:
- external storage から取得するデータは常に入力検証を行ってください。これは、信頼できないソースからのデータであるため非常に重要です。 - external storage から取得したデータに対しては常に入力バリデーションを行ってください。これはデータが信頼できないソースから来るため重要です。
- external storage に実行ファイルや class ファイルを保存して動的にロードすることは強く非推奨です - external storage に実行ファイルや class ファイルを置いて動的にロードすることは強く推奨されません
- もしアプリが external storage から実行ファイルを取得して動的にロードする必要がある場合、それらのファイルは署名され、暗号的に検証されてからロードするようにしてください。これはアプリのセキュリティ整合性を保つために不可欠です。 - もしアプリが external storage から実行可能ファイルを取得しなければならない場合、それらのファイルが署名されており暗号的に検証されていることを確認してから動的にロードしてください。これはアプリのセキュリティ整合性を保つために重要です。
External storage は /storage/emulated/0 , /sdcard , /mnt/sdcard でアクセスできます External storage は `/storage/emulated/0` , `/sdcard` , `/mnt/sdcard` でアクセスできます
> [!TIP] > [!TIP]
> Android 4.4 (**API 17**) 以降、SD card はディレクトリ構造が変更され、アプリからアクセスできるのはそのアプリ専用のディレクトリに限定されるようになりました。これにより、悪意あるアプリが他のアプリのファイルに対して読み取りや書き込みアクセスを得ることを防ぎます。 > Android 4.4 (**API 17**) 以降、SD カードにはアプリごとに特定のディレクトリのみへアクセスを制限するディレクトリ構造が導入されています。これにより、悪意あるアプリが別のアプリのファイルへ読み書きアクセスすることを防ぎます。
**Sensitive data stored in clear-text** **Sensitive data stored in clear-text**
- **Shared preferences**: Android は各アプリが `/data/data/<packagename>/shared_prefs/`簡単に xml ファイルを保存できるようにしており、そのフォルダ内に平文の機密情報が見つかることがあります。 - **Shared preferences**: Android は各アプリが `/data/data/<packagename>/shared_prefs/` XML ファイルを簡単に保存できる仕組みを提供しており、しばしばそのフォルダ内に平文で機密情報が見つかることがあります。
- **Databases**: Android は各アプリが `/data/data/<packagename>/databases/`簡単に sqlite データベースを保存できるようにしており、そのフォルダ内に平文の機密情報が見つかることがあります。 - **Databases**: Android は各アプリが `/data/data/<packagename>/databases/` sqlite データベースを簡単に保存できる仕組みを提供しており、しばしばそのフォルダ内に平文で機密情報が見つかることがあります。
### Broken TLS ### Broken TLS
**Accept All Certificates** **Accept All Certificates**
なぜか開発者がすべての証明書を受け入れてしまうことがあります。例えば hostname が一致しない場合でも以下のようなコード行で受け入れてしまうことがあります: なぜか開発者が全ての証明書を受け入れてしまうことがあり、例えばホスト名が一致しない場合でも以下のようなコード行で検証を無効にしていることがあります。
```java ```java
SSLSocketFactory sf = new cc(trustStore); SSLSocketFactory sf = new cc(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
``` ```
A good way to test this is to try to capture the traffic using some proxy like Burp without authorising Burp CA inside the device. Also, you can generate with Burp a certificate for a different hostname and use it. A good way to test this is to try to capture the traffic using some proxy like Burp without authorising Burp CA inside the device. Also, you can generate with Burp a certificate for a different hostname and use it.
### 脆弱な暗号 ### 暗号の脆弱性
**Poor Key Management Processes** **鍵管理プロセスが不十分**
一部の開発者は機密データをローカルストレージに保存し、コード内にハードコード/予測可能なキーで暗号化します。これはリバースで攻撃者が機密情報を抽出できる可能性があるため避けるべきです。 一部の開発者は機密データをローカルストレージに保存し、コード内にハードコードまたは予測可能なキーで暗号化しています。これは避けるべきで、reversing により攻撃者が機密情報を抽出できる可能性があります。
**Use of Insecure and/or Deprecated Algorithms** **安全でない、または非推奨のアルゴリズムの使用**
開発者は認証チェック、データの保存や送信に**deprecated algorithms**を使うべきではありません。これらのアルゴリズムには RC4, MD4, MD5, SHA1 などがあります。例えばパスワード保存に**hashes**を使う場合は、ソルト付きでブルートフォース耐性のあるハッシュを使用するべきです。 開発者は認可の**checks**、データの**store**や**send**に**deprecated algorithms**を使用すべきではありません。これらのアルゴリズムの例: RC4, MD4, MD5, SHA1... 例えばパスワードを保存するために**hashes**を使用する場合は、ソルトを付けたブルートフォースに**resistant**なハッシュを使用するべきです。
### Other checks ### その他のチェック
- It's recommended to **obfuscate the APK** to difficult the reverse engineer labour to attackers. - APKを難読化して、攻撃者によるリバースエンジニアリングの作業を困難にすることが推奨されます。
- If the app is sensitive (like bank apps), it should perform it's **own checks to see if the mobile is rooted** and act in consequence. - アプリが機密性の高いものであれば銀行系アプリなど、独自にモバイルがrootedかどうかをチェックし、それに応じて対応するべきです。
- If the app is sensitive (like bank apps), it should check if an **emulator** is being used. - アプリが機密性の高いものであれば(銀行系アプリなど)、**emulator**が使用されているかをチェックすべきです。
- If the app is sensitive (like bank apps), it should **check it's own integrity before executing** it to check if it was modified. - アプリが機密性の高いものであれば(銀行系アプリなど)、実行前に自身の整合性をチェックして改変されていないか確認すべきです。
- Use [**APKiD**](https://github.com/rednaga/APKiD) to check which compiler/packer/obfuscator was used to build the APK - [**APKiD**](https://github.com/rednaga/APKiD) を使用して、APK をビルドする際にどの compiler/packer/obfuscator が使われたかを確認してください
### React Native Application ### React Native アプリケーション
Read the following page to learn how to easily access javascript code of React applications: React アプリケーションの javascript コードに簡単にアクセスする方法を知るには、次のページを参照してください:
{{#ref}} {{#ref}}
react-native-application.md react-native-application.md
{{#endref}} {{#endref}}
### Xamarin Applications ### Xamarin アプリケーション
Read the following page to learn how to easily access C# code of a xamarin applications: Xamarin アプリケーションの C# コードに簡単にアクセスする方法を知るには、次のページを参照してください:
{{#ref}} {{#ref}}
../xamarin-apps.md ../xamarin-apps.md
{{#endref}} {{#endref}}
### Superpacked Applications ### Superpacked アプリケーション
According to this [**blog post**](https://clearbluejar.github.io/posts/desuperpacking-meta-superpacked-apks-with-github-actions/) superpacked is a Meta algorithm that compress the content of an application into a single file. The blog talks about the possibility of creating an app that decompress these kind of apps... and a faster way which involves to **execute the application and gather the decompressed files from the filesystem.** According to this [**blog post**](https://clearbluejar.github.io/posts/desuperpacking-meta-superpacked-apks-with-github-actions/) superpacked is a Meta algorithm that compress the content of an application into a single file. The blog talks about the possibility of creating an app that decompress these kind of apps... and a faster way which involves to **execute the application and gather the decompressed files from the filesystem.**
### Automated Static Code Analysis ### 自動静的コード解析
The tool [**mariana-trench**](https://github.com/facebook/mariana-trench) is capable of finding **vulnerabilities** by **scanning** the **code** of the application. This tool contains a series of **known sources** (that indicates to the tool the **places** where the **input** is **controlled by the user**), **sinks** (which indicates to the tool **dangerous** **places** where malicious user input could cause damages) and **rules**. These rules indicates the **combination** of **sources-sinks** that indicates a vulnerability. ツール [**mariana-trench**](https://github.com/facebook/mariana-trench) は、アプリケーションの**code**を**scanning**することで**vulnerabilities**を検出できます。このツールは一連の**known sources**(ツールに対して**input がユーザによって制御される場所**を示す)、**sinks**(悪意あるユーザ入力が被害を引き起こす可能性のある**dangerous な場所**を示す)および**rules**を含みます。これらのルールは、脆弱性を示す**sources-sinks の組み合わせ**を定義します。
With this knowledge, **mariana-trench will review the code and find possible vulnerabilities on it**. この知識により、**mariana-trench はコードをレビューして潜在的な脆弱性を見つけます**。
### Secrets leaked ### Secrets leaked
An application may contain secrets (API keys, passwords, hidden urls, subdomains...) inside of it that you might be able to discover. You could us a tool such as [https://github.com/dwisiswant0/apkleaks](https://github.com/dwisiswant0/apkleaks) アプリケーションには機密情報API keys、passwords、hidden urls、subdomains...)が含まれている可能性があり、これらを発見できる場合があります。次のようなツールを使用できます: [https://github.com/dwisiswant0/apkleaks](https://github.com/dwisiswant0/apkleaks)
### Bypass Biometric Authentication ### Bypass Biometric Authentication
@ -216,14 +215,14 @@ An application may contain secrets (API keys, passwords, hidden urls, subdomains
bypass-biometric-authentication-android.md bypass-biometric-authentication-android.md
{{#endref}} {{#endref}}
### Other interesting functions ### その他の興味深い機能
- **Code execution**: `Runtime.exec(), ProcessBuilder(), native code:system()` - **コード実行**: `Runtime.exec(), ProcessBuilder(), native code:system()`
- **Send SMSs**: `sendTextMessage, sendMultipartTestMessage` - **SMS送信**: `sendTextMessage, sendMultipartTestMessage`
- **Native functions** declared as `native`: `public native, System.loadLibrary, System.load` - **ネイティブ関数**宣言(`native`: `public native, System.loadLibrary, System.load`
- [Read this to learn **how to reverse native functions**](reversing-native-libraries.md) - [これを読んで、**ネイティブ関数をリバースする方法**を学んでください](reversing-native-libraries.md)
### **Other tricks** ### **その他のトリック**
{{#ref}} {{#ref}}
@ -234,157 +233,162 @@ content-protocol.md
--- ---
## Dynamic Analysis ## 動的解析
> First of all, you need an environment where you can install the application and all the environment (Burp CA cert, Drozer and Frida mainly). Therefore, a rooted device (emulated or not) is extremely recommended. > まず、アプリケーションと必要な環境(主に Burp CA cert、Drozer、Fridaをインストールできる環境が必要です。したがって、rooted デバイス(エミュレートされているかどうかに関わらず)が強く推奨されます。
### Online Dynamic analysis ### オンライン動的解析
You can create a **free account** in: [https://appetize.io/](https://appetize.io). This platform allows you to **upload** and **execute** APKs, so it is useful to see how an apk is behaving. 次のサイトで**無料アカウント**を作成できます: [https://appetize.io/](https://appetize.io/)。このプラットフォームでは APK を**upload**して**execute**できるため、APK がどのように動作するかを確認するのに便利です。
You can even **see the logs of your application** in the web and connect through **adb**. ウェブ上でアプリケーションのログを閲覧したり、**adb**で接続したりできます。
![](<../../images/image (831).png>) ![](<../../images/image (831).png>)
Thanks to the ADB connection you can use **Drozer** and **Frida** inside the emulators. ADB 接続によりエミュレータ内で **Drozer****Frida** を使用できます。
### Local Dynamic Analysis ### ローカル動的解析
#### Using an emulator #### エミュレータを使用する場合
- [**Android Studio**](https://developer.android.com/studio) (You can create **x86** and **arm** devices, and according to [**this** ](https://android-developers.googleblog.com/2020/03/run-arm-apps-on-android-emulator.html)**latest x86** versions **support ARM libraries** without needing an slow arm emulator). - [**Android Studio**](https://developer.android.com/studio)**x86** および **arm** デバイスを作成できます。さらに [**this**](https://android-developers.googleblog.com/2020/03/run-arm-apps-on-android-emulator.html) によると **最新の x86** バージョンは遅い arm エミュレータを必要とせずに **ARM ライブラリをサポート**します)。
- Learn to set it up in this page: - セットアップ方法は次のページを参照してください:
{{#ref}} {{#ref}}
avd-android-virtual-device.md avd-android-virtual-device.md
{{#endref}} {{#endref}}
- [**Genymotion**](https://www.genymotion.com/fun-zone/) **(Free version:** Personal Edition, you need to create an account. _It's recommend to **download** the version **WITH**_ _**VirtualBox** to avoid potential errors._) - [**Genymotion**](https://www.genymotion.com/fun-zone/) **(無料版:** Personal Edition、アカウント作成が必要です。_潜在的なエラーを避けるために**VirtualBox**付きのバージョンを**ダウンロード**することを推奨します._
- [**Nox**](https://es.bignox.com) (Free, but it doesn't support Frida or Drozer). - [**Nox**](https://es.bignox.com)無料ですが、Frida や Drozer はサポートしていません)。
> [!TIP] > [!TIP]
> When creating a new emulator on any platform remember that the bigger the screen is, the slower the emulator will run. So select small screens if possible. > 新しいエミュレータを作成する際は、画面が大きいほどエミュレータの動作が遅くなることに注意してください。可能であれば小さい画面を選んでください。
To **install google services** (like AppStore) in Genymotion you need to click on the red marked button of the following image: Genymotion に **google services**AppStore など)を**インストール**するには、次の画像の赤いマークのボタンをクリックする必要があります:
![](<../../images/image (277).png>) ![](<../../images/image (277).png>)
Also, notice that in the **configuration of the Android VM in Genymotion** you can select **Bridge Network mode** (this will be useful if you will be connecting to the Android VM from a different VM with the tools). また、Genymotion の **Android VM の構成**で **Bridge Network mode** を選択できることに注意してください(これは、ツールを実行する別の VM から Android VM に接続する場合に便利です)。
#### Use a physical device #### 実機を使用する場合
You need to activate the **debugging** options and it will be cool if you can **root** it: デバッグオプションを有効にする必要があり、可能であれば root 化することを推奨します:
1. **Settings**. 1. **設定**.
2. (FromAndroid 8.0) Select **System**. 2. (Android 8.0以降) **システム** を選択.
3. Select **About phone**. 3. **端末情報** を選択.
4. Press **Build number** 7 times. 4. **ビルド番号** を7回押す.
5. Go back and you will find the **Developer options**. 5. 戻ると **開発者向けオプション** が表示されます.
> Once you have installed the application, the first thing you should do is to try it and investigate what does it do, how does it work and get comfortable with it.\ > アプリをインストールしたら、まず最初にそれを試して、何をするのか、どのように動作するのかを調査し、使い方に慣れてください。\
> I will suggest to **perform this initial dynamic analysis using MobSF dynamic analysis + pidcat**, so we will be able to **learn how the application works** while MobSF **captures** a lot of **interesting** **data** you can review later on. > 初期の動的解析は **MobSF dynamic analysis + pidcat** を使用して行うことをお勧めします。そうすることで、MobSF が後で確認できる多くの**興味深いデータ**をキャプチャしながら、アプリの動作を学ぶことができます。
Magisk/Zygisk クイックートPixel デバイスで推奨)
- Magisk アプリで boot.img をパッチし、fastboot 経由でフラッシュして systemless root を取得する
- root 隠蔽のために Zygisk + DenyList を有効にする;より強力な隠蔽が必要な場合は LSPosed/Shamiko を検討する
- OTA アップデートから復旧できるように元の boot.img を保管しておく;各 OTA 後に再パッチする
- 画面ミラーリングにはホスト上で scrcpy を使用する
### Unintended Data Leakage ### Unintended Data Leakage
**Logging** **ログ出力**
開発者は**debugging information**を公開しないよう注意すべきです。これは機密データのleakにつながる可能性があります。アプリケーションログを監視して機密情報を特定・保護するために [**pidcat**](https://github.com/JakeWharton/pidcat) や `adb logcat` を使うことを推奨します。**Pidcat**は使いやすさと可読性の面で好まれます。 開発者は**debugging information**を公開すると機密データの leak を招く可能性があるため注意すべきです。アプリケーションログを監視して機密情報を特定・保護するには、[**pidcat**](https://github.com/JakeWharton/pidcat) と `adb logcat` を推奨します。**Pidcat** は使いやすさと可読性から好まれます。
> [!WARNING] > [!WARNING]
> Note that from **later newer than Android 4.0**, **applications are only able to access their own logs**. So applications cannot access other apps logs.\ > **Android 4.0 以降**では、**アプリケーションは自身のログにのみアクセス可能**です。したがって、アプリは他のアプリのログにアクセスできません。\
> Anyway, it's still recommended to **not log sensitive information**. > それでも、機密情報をログに記録しないことを推奨します。
**Copy/Paste Buffer Caching** **コピー/ペースト バッファのキャッシュ**
Androidの**clipboard-based**フレームワークはアプリのコピー&ペーストを可能にしますが、**他のアプリ**がクリップボードにアクセスできるため、機密データが露出するリスクがあります。クレジットカード情報などの機密セクションではコピー/ペースト機能を無効にすることが重要です。 Android **clipboard-based** フレームワークはアプリのコピー&ペースト機能を可能にしますが、**他のアプリケーション**がクリップボードに**アクセス**できるため、機密データが露出するリスクがあります。クレジットカード情報など機密性の高い箇所では、コピー/ペースト機能を無効にして data leak を防ぐことが重要です。
**Crash Logs** **クラッシュログ**
アプリが**クラッシュ**してログを保存する場合、これらのログはリバースが困難な場合でも攻撃者に手がかりを与えることがあります。このリスクを軽減するため、クラッシュ時に不要なログを残さない、またはログをネットワーク送信する場合はSSL経由で送るようにしてください。 アプリケーションが**クラッシュ**して**ログを保存**する場合、これらのログは特にアプリをリバースエンジニアリングできない状況で攻撃者の助けとなる可能性があります。このリスクを軽減するため、クラッシュ時のログ記録は避け、もしログをネットワーク経由で送信する必要がある場合は SSL チャネルで送信するようにしてください。
ペンテスターとして、**これらのログを確認することを試みてください** pentester として、**これらのログを確認する**ことを試みてください
**Analytics Data Sent To 3rd Parties** **サードパーティへ送信される分析データ**
多くのアプリは Google Adsense のようなサービスを統合しており、開発者の誤実装により機密データが誤ってthird-partyにleakすることがあります。潜在的なデータ漏洩を特定するには、アプリのトラフィックをインターセプトして、サードパーティに送信される機密情報がないか確認することを勧めます。 アプリはしばしば Google Adsense のようなサービスを統合していますが、開発者の実装ミスにより機密データを意図せずに leak してしまうことがあります。潜在的な data leak を特定するには、アプリのトラフィックを intercept して、サードパーティへ送信されている機密情報がないか確認することをお勧めします。
### SQLite DBs ### SQLite DBs
ほとんどのアプリは情報を保存するために**internal SQLite databases**を使用します。ペンテスト中は作成された**databases**、**tables**や**columns**の名前、保存されている**data**を確認してください。機密情報が見つかる可能性がありますこれがvulnerabilityとなります。\ 多くのアプリは情報を保存するために **内部の SQLite データベース** を使用します。pentest 中は作成された **databases**、**tables** や **columns** の名前、保存されているすべての **data** を確認してください。機密情報が見つかる可能性があり(それは脆弱性になります)。データベースは通常 `/data/data/the.package.name/databases` にあり、例: `/data/data/com.mwr.example.sieve/databases`
データベースは通常 `/data/data/the.package.name/databases` に存在します(例: `/data/data/com.mwr.example.sieve/databases`)。
データベースが機密情報を保存していて**encrypted**されていても、アプリ内でその**password**を**find**できる場合は、依然として**vulnerability**です。 データベースが機密情報を保存しており**暗号化されている**場合でも、その**password**をアプリ内で**見つけられる**なら、それは依然として**脆弱性**です。
テーブルの一覧`.tables`テーブルのカラムは `.schema <table_name>`列挙します テーブルは `.tables` で列挙し、テーブルのカラムは `.schema <table_name>`確認してください
### Drozer (Exploit Activities, Content Providers and Services) ### Drozer (Exploit Activities, Content Providers and Services)
From [Drozer Docs](https://labs.mwrinfosecurity.com/assets/BlogFiles/mwri-drozer-user-guide-2015-03-23.pdf): **Drozer** allows you to **assume the role of an Android app** and interact with other apps. It can do **anything that an installed application can do**, such as make use of Androids Inter-Process Communication (IPC) mechanism and interact with the underlying operating system. .\ From [Drozer Docs](https://labs.mwrinfosecurity.com/assets/BlogFiles/mwri-drozer-user-guide-2015-03-23.pdf): **Drozer** allows you to **assume the role of an Android app** and interact with other apps. It can do **anything that an installed application can do**, such as make use of Androids Inter-Process Communication (IPC) mechanism and interact with the underlying operating system. .\
Drozer is s useful tool to **exploit exported activities, exported services and Content Providers** as you will learn in the following sections. Drozer is s useful tool to **exploit exported activities, exported services and Content Providers** as you will learn in the following sections.
### Exploiting exported Activities ### エクスポートされた Activity の悪用
[**Read this if you want to refresh what is an Android Activity.**](android-applications-basics.md#launcher-activity-and-other-activities)\ [**Android Activity とは何かを再確認したい場合はこれを読んでください。**](android-applications-basics.md#launcher-activity-and-other-activities)\
Also remember that the code of an activity starts in the **`onCreate`** method. また、Activity のコードは **`onCreate`** メソッドから始まることを覚えておいてください。
**Authorisation bypass** **Authorisation bypass**
When an Activity is exported you can invoke its screen from an external app. Therefore, if an activity with **sensitive information** is **exported** you could **bypass** the **authentication** mechanisms **to access it.** Activity が exported されている場合、外部アプリからその画面を呼び出せます。したがって、**sensitive information** を含む Activity が **exported** されていると、認証メカニズムを **bypass** してアクセスされる可能性があります。
[**Learn how to exploit exported activities with Drozer.**](drozer-tutorial/index.html#activities) [**Drozer でエクスポートされた activities を悪用する方法を学ぶ。**](drozer-tutorial/index.html#activities)
You can also start an exported activity from adb: また、adb から exported activity を起動することもできます:
- PackageName is com.example.demo - PackageName com.example.demo
- Exported ActivityName is com.example.test.MainActivity - Exported ActivityName com.example.test.MainActivity
```bash ```bash
adb shell am start -n com.example.demo/com.example.test.MainActivity adb shell am start -n com.example.demo/com.example.test.MainActivity
``` ```
**注意**: MobSF は activity の `android:launchMode`_**singleTask/singleInstance**_ を使用していることを悪意あるものとして検出しますが、[これ](https://github.com/MobSF/Mobile-Security-Framework-MobSF/pull/750) によると、これは古いバージョンAPI versions < 21のみ危険なようです **NOTE**: MobSF will detect as malicious the use of _**singleTask/singleInstance**_ as `android:launchMode` in an activity, but due to [this](https://github.com/MobSF/Mobile-Security-Framework-MobSF/pull/750), apparently this is only dangerous on old versions (API versions < 21).
> [!TIP] > [!TIP]
> 認可 bypass が必ずしも脆弱性になるとは限らない点に注意してください。bypass の仕組みや露出する情報によって判断されます。 > 認可バイパスが必ずしも脆弱性であるとは限らないことに注意してください。脆弱性かどうかは、バイパスの仕組みやどの情報が露出するかによります。
**機密情報の leak** **機密情報漏洩**
**Activities は結果を返すこともあります**。exported かつ保護されていない activity が **`setResult`** メソッドを呼び出し **機密情報を返している** のを見つけた場合、機密情報の leak が発生します。 **Activitiesは結果を返すこともあります**。exportedかつ保護されていないアクティビティが**`setResult`**メソッドを呼び出して**機密情報を返している**場合、機密情報の漏洩があります。
#### Tapjacking #### Tapjacking
Tapjacking が防止されていない場合、exported activity を悪用して **user に予期しない操作を実行させる** ことができます。詳細は [**Tapjacking とは(リンク参照)**](#tapjacking) を参照してください。 Tapjackingが防止されていない場合、exportedなアクティビティを悪用して**ユーザーに予期しない操作を行わせる**ことができます。詳細は[**what is Tapjacking follow the link**](#tapjacking)を参照してください。
### Exploiting Content Providers - Accessing and manipulating sensitive information ### Exploiting Content Providers - Accessing and manipulating sensitive information
[**Content Provider を再確認したい場合はこちらを読んでください。**](android-applications-basics.md#content-provider)\ [**Read this if you want to refresh what is a Content Provider.**](android-applications-basics.md#content-provider)\
Content providers は基本的にデータを**共有**するために使用されます。アプリに利用可能な content providers があれば、そこから**機密データを抽出**できる可能性があります。脆弱であることがあるため、**SQL injections** や **Path Traversals** のテストを行うことも重要です。 Content providersは基本的に**データを共有する**ために使われます。アプリに利用可能なcontent providersがある場合、そこから**機密データを抽出**できる可能性があります。また、脆弱である可能性があるため、**SQL injections**や**Path Traversals**のテストを行うことも重要です。
[**Learn how to exploit Content Providers with Drozer.**](drozer-tutorial/index.html#content-providers) [**Learn how to exploit Content Providers with Drozer.**](drozer-tutorial/index.html#content-providers)
### **Exploiting Services** ### **Exploiting Services**
[**Service を再確認したい場合はこちらを読んでください。**](android-applications-basics.md#services)\ [**Read this if you want to refresh what is a Service.**](android-applications-basics.md#services)\
Service の処理は `onStartCommand` メソッドで開始されることを忘れないでください。 Serviceの動作は`onStartCommand`メソッドから始まることを覚えておいてください。
Service は基本的にデータを**受け取り**、**処理**し、(する場合には)レスポンスを**返す**ものです。したがって、アプリがいくつかのサービスを export している場合は、何をしているのかを理解するために**コード**を**確認**し、機密情報の抽出や認証の bypass などを目的に**動的に**テストするべきです。\ Serviceは基本的にデータを**受け取り**、それを**処理**し、(場合によっては)レスポンスを**返す**ものです。したがって、アプリがいくつかのServiceをexportしている場合は、何をしているかを理解するために**コードを確認**し、機密情報の抽出や認可回避などを目的として**動的にテスト**するべきです。\
[**Learn how to exploit Services with Drozer.**](drozer-tutorial/index.html#services) [**Learn how to exploit Services with Drozer.**](drozer-tutorial/index.html#services)
### **Exploiting Broadcast Receivers** ### **Exploiting Broadcast Receivers**
[**Broadcast Receiver を再確認したい場合はこちらを読んでください。**](android-applications-basics.md#broadcast-receivers)\ [**Read this if you want to refresh what is a Broadcast Receiver.**](android-applications-basics.md#broadcast-receivers)\
Broadcast Receiver の処理は `onReceive` メソッドで開始されることを忘れないでください。 Broadcast Receiverの動作は`onReceive`メソッドから始まることを覚えておいてください。
Broadcast receiver は特定の種類のメッセージを待機します。受け取ったメッセージの処理方法によっては脆弱になる可能性があります。\ Broadcast receiverは特定の種類のメッセージを待ち受けます。受信側がそのメッセージをどのように処理するかによって、脆弱になる可能性があります。\
[**Learn how to exploit Broadcast Receivers with Drozer.**](#exploiting-broadcast-receivers) [**Learn how to exploit Broadcast Receivers with Drozer.**](#exploiting-broadcast-receivers)
### **Exploiting Schemes / Deep links** ### **Exploiting Schemes / Deep links**
deep links は手動で探すこともできます。MobSF のようなツールや [this one](https://github.com/ashleykinguk/FBLinkBuilder/blob/master/FBLinkBuilder.py) のようなスクリプトを使ってください。\ deep linksは手動で探すこともでき、MobSFのようなツールや[このスクリプト](https://github.com/ashleykinguk/FBLinkBuilder/blob/master/FBLinkBuilder.py)のようなものを使えます。\
宣言された **scheme****adb****browser** を使って **open** できます: 宣言された**scheme**は、**adb**や**browser**を使って**開く**ことができます:
```bash ```bash
adb shell am start -a android.intent.action.VIEW -d "scheme://hostname/path?param=value" [your.package.name] adb shell am start -a android.intent.action.VIEW -d "scheme://hostname/path?param=value" [your.package.name]
``` ```
_**package name を省略**すると、モバイルはそのリンクを開くべきアプリを自動的に呼び出します._ _注意: **パッケージ名を省略**すると、モバイルはそのリンクを開くべきアプリを自動的に呼び出します._
```html ```html
<!-- Browser regular link --> <!-- Browser regular link -->
<a href="scheme://hostname/path?param=value">Click me</a> <a href="scheme://hostname/path?param=value">Click me</a>
@ -393,55 +397,56 @@ _**package name を省略**すると、モバイルはそのリンクを開く
``` ```
**実行されるコード** **実行されるコード**
アプリで**実行されるコード**を見つけるには、deeplink によって呼び出される activity に移動し、関数 **`onNewIntent`** を検索してください。 アプリで**実行されるコード**を見つけるには、deeplink によって呼れる activity に移動し、関数 **`onNewIntent`** を検索してください。
![](<../../images/image (436) (1) (1) (1).png>) ![](<../../images/image (436) (1) (1) (1).png>)
**機密情報** **機密情報**
deep link を見つけたら毎回、**URL パラメータ経由でパスワードのような機密データを受け取っていないか**を確認してください。そうでないと、他のアプリがその deep link を **impersonate してデータを盗む**可能性があります! deep link を見つけたら、必ず **URL パラメータ経由で機密情報(例えば passwordsが渡されていないか** を確認してください。なぜなら他のアプリがその deep link を **なりすましてデータを盗む** 可能性があるからです!
パス内のパラメータ **パス内の Parameters**
You **must check also if any deep link is using a parameter inside the path** of the URL like: `https://api.example.com/v1/users/{username}` , in that case you can force a path traversal accessing something like: `example://app/users?username=../../unwanted-endpoint%3fparam=value` .\
Note that if you find the correct endpoints inside the application you may be able to cause a **Open Redirect** (if part of the path is used as domain name), **account takeover** (if you can modify users details without CSRF token and the vuln endpoint used the correct method) and any other vuln. More [info about this here](http://dphoeniixx.com/2020/12/13-2/). URL のパス内でパラメータを使っている deep link がないかも **必ず確認** してください。例えば `https://api.example.com/v1/users/{username}` のような場合、次のように path traversal を強制できることがあります:`example://app/users?username=../../unwanted-endpoint%3fparam=value` 。\
アプリ内で正しいエンドポイントを見つけられれば、パスの一部がドメイン名として使われていた場合の **Open Redirect**、CSRF token なしでユーザ詳細を変更できる場合の **account takeover**、その他の脆弱性を引き起こせる可能性があります。詳細は [info about this here](http://dphoeniixx.com/2020/12/13-2/) を参照してください。
**More examples** **More examples**
リンク_/.well-known/assetlinks.json_に関する[興味深い bug bounty レポート](https://hackerone.com/reports/855618)。 興味深いバグバウンティレポートの例:[https://hackerone.com/reports/855618](https://hackerone.com/reports/855618)リンクに関する報告、_/.well-known/assetlinks.json_
### Transport Layer Inspection and Verification Failures ### トランスポート層の検査と検証の失敗
- **Certificates are not always inspected properly** by Android applications. 多くのアプリは警告を見落とし、自己署名証明書を受け入れたり、場合によっては HTTP 接続にフォールバックすることがあります。 - **Certificates are not always inspected properly** by Android applications. 多くのアプリは警告を見落とし、self-signed certificates を受け入れたり、場合によっては HTTP 接続に戻してしまうことがあります。
- **Negotiations during the SSL/TLS handshake are sometimes weak**, insecure な cipher suites を使用していることがあります。この脆弱性により接続は man-in-the-middle (MITM) 攻撃に対して脆弱になり、攻撃者がデータを復号できる可能性があります。 - **Negotiations during the SSL/TLS handshake are sometimes weak**, insecure な cipher suites を用いていることがあります。この脆弱性により接続が man-in-the-middle (MITM) 攻撃に対して脆弱になり、攻撃者がデータを復号できる可能性があります。
- **Leakage of private information** は、アプリがセキュアなチャネルで認証を行った後に他のトランザクションで非セキュアなチャネルを使って通信する場合にリスクとなります。この手法では、セッションクッキーやユーザー情報などの機密データが悪意ある第三者によって傍受されるおそれがあります - Leakage of private information は、アプリが認証だけ secure なチャネルを使い、他の取引を非secure なチャネルで行う場合にリスクとなります。このやり方はセッション cookie やユーザ詳細などの機密データを悪意ある第三者による傍受から守れません
#### Certificate Verification #### 証明書の検証
ここでは **certificate verification** に焦点を当てます。サーバー証明書の整合性を検証することはセキュリティ向上のために必須です。これは、不適切な TLS 構成や暗号化されていないチャネルでの機密データ送信が重大なリスクを引き起こすためです。サーバー証明書の検証手順や脆弱性への対処方法の詳細は、[**this resource**](https://manifestsecurity.com/android-application-security-part-10/) を参照してください。 ここでは **certificate verification** に焦点を当てます。サーバの証明書の整合性を検証することはセキュリティ強化に不可欠です。insecure な TLS 設定や暗号化されていないチャネルで機密データを送信することは重大なリスクを招くためです。サーバ証明書の検証手順や脆弱性対応の詳細については、[**this resource**](https://manifestsecurity.com/android-application-security-part-10/) を参照してください。
#### SSL Pinning #### SSL Pinning
SSL Pinning は、アプリがサーバー証明書をアプリ内に格納された既知のコピーと照合して検証するセキュリティ手法です。これは MITM 攻撃を防ぐために重要です。機密情報を扱うアプリケーションでは SSL Pinning の実装が強く推奨されます。 SSL Pinning は、アプリがサーバの証明書をアプリ内に保存された既知のコピーと照合するセキュリティ対策です。この手法は MITM 攻撃を防ぐ上で重要です。機密情報を扱うアプリでは SSL Pinning の実装を強く推奨します。
#### Traffic Inspection #### トラフィック検査
HTTP トラフィックを検査するには、プロキシツールの証明書(例: Burp**インストールする必要があります**。この証明書をインストールしないと、暗号化されたトラフィックはプロキシ経由で見えないことがあります。カスタム CA 証明書のインストール方法は、[**click here**](avd-android-virtual-device.md#install-burp-certificate-on-a-virtual-machine) を参照してください。 HTTP トラフィックを検査するには、プロキシツールの証明書(例Burp**インストールする必要があります**。この証明書をインストールしないと、暗号化されたトラフィックはプロキシ上で見えない可能性があります。カスタム CA 証明書のインストール手順については [**click here**](avd-android-virtual-device.md#install-burp-certificate-on-a-virtual-machine) を参照してください。
API Level 24 以上をターゲットにするアプリは、プロキシの CA 証明書を受け入れるために Network Security Config を変更する必要があります。暗号化トラフィックを検査するための Network Security Config の変更手順は、[**refer to this tutorial**](make-apk-accept-ca-certificate.md) を参照してください。 Applications targeting **API Level 24 and above** は、プロキシの CA 証明書を受け入れるよう Network Security Config を変更する必要があります。暗号化されたトラフィックを検査するにはこの手順が重要です。Network Security Config の変更手順については [**refer to this tutorial**](make-apk-accept-ca-certificate.md) を確認してください。
もし **Flutter** を使用している場合は、[**this page**](flutter.md) の指示に従う必要があります。単に証明書をストアに追加するだけでは機能しません。Flutter は独自の有効な CA リストを持っているためです。 もし **Flutter** を使用している場合は、[**this page**](flutter.md) の指示に従ってください。単に証明書をストアに追加するだけでは動作しないことがあり、Flutter は独自の有効な CA リストを持っているためです。
#### Static detection of SSL/TLS pinning #### SSL/TLS pinning の静的検出
ランタイムでのバイパスを試みる前に、まず APK 内でどこに pinning が強制されているかを素早くマップしてください。静的検出は、フックやパッチの計画を立て、適切なコードパスに集中するのに役立ちます。 runtime bypass を試みる前に、まず APK 内で pinning がどこに強制されているかを素早くマップしてください。静的検出によりフック/パッチの計画が立てやすく、正しいコードパスに集中できます。
Tool: SSLPinDetect Tool: SSLPinDetect
- APK を Smali にデコンパイルapktool 経由して、SSL/TLS pinning 実装のためにキュレートされた正規表現パターンをスキャンするオープンソースの静的解析ユーティリティ。 - オープンソースの static-analysis ユーティリティで、apk を Smaliapktool 経由にデコンパイルし、SSL/TLS pinning 実装のためにキュレーションされた regex パターンをスキャンします。
- 各マッチについて、正確なファイルパス、行番号、コードスニペットを報告します。 - 各一致について正確なファイルパス、行番号、コードスニペットを報告します。
- OkHttp CertificatePinner、カスタム javax.net.ssl.X509TrustManager.checkServerTrusted、SSLContext.init with custom TrustManagers/KeyManagers、Network Security Config XML pins などの一般的なフレームワークやカスタムコードパスをカバーします。 - OkHttp CertificatePinner、カスタム `javax.net.ssl.X509TrustManager.checkServerTrusted``SSLContext.init`(カスタム TrustManagers/KeyManagers 使用)や Network Security Config XML pins など、一般的なフレームワークとカスタムコードパスをカバーします。
Install Install
- 前提条件: Python >= 3.8, Java on PATH, apktool - Prereqs: Python >= 3.8, Java on PATH, apktool
```bash ```bash
git clone https://github.com/aancw/SSLPinDetect git clone https://github.com/aancw/SSLPinDetect
cd SSLPinDetect cd SSLPinDetect
@ -456,8 +461,7 @@ python sslpindetect.py -f app.apk -a apktool.jar
python sslpindetect.py -a apktool_2.11.0.jar -f sample/app-release.apk -v python sslpindetect.py -a apktool_2.11.0.jar -f sample/app-release.apk -v
``` ```
パターンルールの例 (JSON) パターンルールの例 (JSON)
独自/カスタムのpinningスタイルを検出するために、signaturesを使用または拡張してください。独自のJSONを読み込み、大規模にscanを実行できます。
signatures を使用または拡張して proprietary/custom pinning styles を検出します。自分の JSON を読み込んで、大規模にスキャンできます。
```json ```json
{ {
"OkHttp Certificate Pinning": [ "OkHttp Certificate Pinning": [
@ -471,43 +475,41 @@ signatures を使用または拡張して proprietary/custom pinning styles を
] ]
} }
``` ```
Notes and tips 注意とヒント
- 大規模なアプリに対してはマルチスレッディングとメモリマップドI/Oで高速スキャンする事前コンパイル済みのregexはオーバーヘッド誤検知を減らす。 - 大規模なアプリをマルチスレッディングと memory-mapped I/O で高速スキャン;事前コンパイル済みの regex はオーバーヘッドと誤検知を減らします。
- Pattern collection: https://github.com/aancw/smali-sslpin-patterns - Pattern collection: https://github.com/aancw/smali-sslpin-patterns
- 次にトリアージすべき典型的な検出対象 - 次にトリアージすべき典型的な検出対象:
- OkHttp: CertificatePinner usage, setCertificatePinner, okhttp3/okhttp package references - OkHttp: CertificatePinner の使用、setCertificatePinner、okhttp3/okhttp パッケージ参照
- Custom TrustManagers: javax.net.ssl.X509TrustManager, checkServerTrusted overrides - カスタム TrustManagers: javax.net.ssl.X509TrustManager、checkServerTrusted のオーバーライド
- Custom SSL contexts: SSLContext.getInstance + SSLContext.init with custom managers - カスタム SSL contexts: SSLContext.getInstance + SSLContext.init とカスタムマネージャ
- Declarative pins in res/xml network security config and manifest references - res/xml network security config と manifest の宣言的ピン設定
- 一致した箇所を利用して、dynamic testing の前に Frida hooks、static patches、または設定レビューを計画する。 - マッチした箇所を使って、Frida フック、静的パッチ、または設定レビューを動的テストの前に計画する。
#### SSL Pinning の回避
SSL Pinning が実装されている場合、HTTPS トラフィックを検査するためにそれを回避する必要があります。目的のために利用できる方法はいくつかあります:
#### SSL Pinningの回避 - 自動的に **変更** して **apk****バイパス** するために [**apk-mitm**](https://github.com/shroudedcode/apk-mitm) を使う。 この方法の最大の利点は、SSL Pinning を回避するのに root が不要であることだが、アプリを削除して新しいものを再インストールする必要があり、常に動作するとは限らない。
- この保護を回避するために **Frida**後述を使うこともできる。Burp+Frida+Genymotion を使うガイド: [https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/](https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/)
- [**objection**](frida-tutorial/objection-tutorial.md) を使って **自動的に SSL Pinning をバイパス** することも試せます:**:** `objection --gadget com.package.app explore --startup-command "android sslpinning disable"`
- **MobSF dynamic analysis** を使って **自動的に SSL Pinning をバイパス** することも試せます(以下に説明)
- まだ取得できていないトラフィックがあると思われる場合は、iptables を使ってトラフィックを Burp に **転送する** ことを試せます。この記事を読む: [https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62](https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62)
SSL Pinning が実装されている場合、HTTPSトラフィックを調査するためにそれを回避する必要がある。これにはいくつかの方法がある #### 一般的な Web 脆弱性の探索
- 自動的に **apk** を修正して **SSLPinning****bypass** するために [**apk-mitm**](https://github.com/shroudedcode/apk-mitm) を使う。 この方法の最大の利点は、SSLPinning を回避するのに root が不要なことだが、アプリを削除して再インストールする必要があり、常に動作するとは限らない。 アプリ内の一般的な Web 脆弱性も検索することが重要です。これら脆弱性の特定と緩和に関する詳細はこの要約の範囲外ですが、他所で広く解説されています。
- この保護を回避するために **Frida**下で説明を使うこともできる。Burp+Frida+Genymotion を使うガイドはこちら: [https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/](https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/)
- [**objection**](frida-tutorial/objection-tutorial.md) を使って **自動的に SSL Pinning を回避** することも試せる**** `objection --gadget com.package.app explore --startup-command "android sslpinning disable"`
- **MobSF dynamic analysis**(下で説明)を使って **自動的に SSL Pinning を回避** することも試せる。
- それでも捕捉できていないトラフィックがあると思う場合は、iptables を使ってトラフィックを burp に転送することを試してみる。こちらのブログを読むと良い: [https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62](https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62)
#### 一般的なWeb脆弱性の探索
アプリ内で一般的なWeb脆弱性を探すことも重要だ。これらの脆弱性の特定や緩和に関する詳細はこの要約の範囲を超えるが、他の資料で詳しく扱われている。
### Frida ### Frida
[Frida](https://www.frida.re) は開発者、リバースエンジニア、セキュリティ研究者向けのダイナミックなインストルメンテーションツールキットだ。\ [Frida](https://www.frida.re) は開発者、リバースエンジニア、セキュリティ研究者向けの動的インストルメンテーションツールキットです。\
**実行中のアプリにアクセスして、ランタイムでメソッドにhookを仕込み、挙動や値を変更したり、値を抽出したり、別のコードを実行したりできる。**\ **実行中のアプリケーションにアクセスしてランタイムでメソッドにフックし、振る舞いを変えたり、値を変更したり、値を抽出したり、別のコードを実行したりできます...**\
Androidアプリをpentestするなら Frida の使い方を知っておく必要がある Android アプリを pentest するなら、Frida の使い方を知っておく必要があります。
- Learn how to use Frida: [**Frida tutorial**](frida-tutorial/index.html) - Frida の使い方を学ぶ: [**Frida tutorial**](frida-tutorial/index.html)
- Some "GUI" for actions with Frida: [**https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security**](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security) - Frida 操作のための「GUI」的ツール: [**https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security**](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security)
- Ojection is great to automate the use of Frida: [**https://github.com/sensepost/objection**](https://github.com/sensepost/objection) **,** [**https://github.com/dpnishant/appmon**](https://github.com/dpnishant/appmon) - Ojection は Frida の利用を自動化するのに便利: [**https://github.com/sensepost/objection**](https://github.com/sensepost/objection) **,** [**https://github.com/dpnishant/appmon**](https://github.com/dpnishant/appmon)
- You can find some Awesome Frida scripts here: [**https://codeshare.frida.re/**](https://codeshare.frida.re) - いくつかの Awesome Frida スクリプト: [**https://codeshare.frida.re/**](https://codeshare.frida.re)
- Try to bypass anti-debugging / anti-frida mechanisms loading Frida as in indicated in [https://erfur.github.io/blog/dev/code-injection-without-ptrace](https://erfur.github.io/blog/dev/code-injection-without-ptrace) (tool [linjector](https://github.com/erfur/linjector-rs)) - Frida をロードして anti-debugging / anti-frida 機構を回避することを試す: [https://erfur.github.io/blog/dev/code-injection-without-ptrace](https://erfur.github.io/blog/dev/code-injection-without-ptrace)(ツール [linjector](https://github.com/erfur/linjector-rs)
#### Anti-instrumentation & SSL pinning bypass workflow #### Anti-instrumentation & SSL pinning bypass workflow
@ -515,11 +517,11 @@ Androidアプリをpentestするなら Frida の使い方を知っておく必
android-anti-instrumentation-and-ssl-pinning-bypass.md android-anti-instrumentation-and-ssl-pinning-bypass.md
{{#endref}} {{#endref}}
### **Dump Memory - Fridump** ### **メモリダンプ - Fridump**
アプリがパスワードやニーモニックなど、本来メモリに保持すべきでない機密情報をメモリ内に保存していないか確認する アプリがパスワードやニーモニック(シードフレーズ)など、本来メモリ内に保持すべきでない機密情報を保存していないか確認してください
Using [**Fridump3**](https://github.com/rootbsd/fridump3) you can dump the memory of the app with: [**Fridump3**](https://github.com/rootbsd/fridump3) を使うと、以下のようにアプリのメモリをダンプできます:
```bash ```bash
# With PID # With PID
python3 fridump3.py -u <PID> python3 fridump3.py -u <PID>
@ -528,76 +530,77 @@ python3 fridump3.py -u <PID>
frida-ps -Uai frida-ps -Uai
python3 fridump3.py -u "<Name>" python3 fridump3.py -u "<Name>"
``` ```
これにより ./dump フォルダにメモリがダンプされ、そこで次のように grep できます: これにより ./dump フォルダにメモリが dump され、そこで次のように grep できます:
```bash ```bash
strings * | grep -E "^[a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+$" strings * | grep -E "^[a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+$"
``` ```
### **Keystore内の機密データ** ### **Keystore内の機密データ**
AndroidではKeystoreは機密データを保存する最適な場所ですが、権限が十分あれば**アクセス可能**な場合があります。アプリはここに**機密データをプレーンテキストで保存する**傾向があるため、pentestsではrootユーザーとして確認する必要があります。物理的にデバイスにアクセスできる者がこのデータを盗む可能性があります。 AndroidではKeystoreが機密データを保存する最良の場所ですが、十分な権限があればそれでも**アクセス可能です**。
アプリケーションはここに**平文の機密データ**を保存する傾向があるため、pentestsはこれを確認するべきです。root userやデバイスに物理的にアクセスできる者がこのデータを盗める可能性があります。
アプリがKeystoreにデータを保存している場合でも、データは暗号化されているべきです。 アプリがkeystoreにデータを保存している場合でも、そのデータは暗号化されているべきです。
Keystore内のデータにアクセスするには、このFridaスクリプトを使用できます: [https://github.com/WithSecureLabs/android-keystore-audit/blob/master/frida-scripts/tracer-cipher.js](https://github.com/WithSecureLabs/android-keystore-audit/blob/master/frida-scripts/tracer-cipher.js) keystore内のデータにアクセスするには、次のFridaスクリプトを使用できます: [https://github.com/WithSecureLabs/android-keystore-audit/blob/master/frida-scripts/tracer-cipher.js](https://github.com/WithSecureLabs/android-keystore-audit/blob/master/frida-scripts/tracer-cipher.js)
```bash ```bash
frida -U -f com.example.app -l frida-scripts/tracer-cipher.js frida -U -f com.example.app -l frida-scripts/tracer-cipher.js
``` ```
### **Fingerprint/Biometrics Bypass** ### **Fingerprint/Biometrics Bypass**
以下のFridaスクリプトを使用すると、Androidアプリが特定の機密領域を保護するために実施している可能性のある **bypass fingerprint authentication** を回避できる場合があります: 以下のFridaスクリプトを使用すると、Androidアプリケーションが**特定の機密領域を保護するために**実行している**bypass fingerprint authentication**を回避できる可能性があります:
```bash ```bash
frida --codeshare krapgras/android-biometric-bypass-update-android-11 -U -f <app.package> frida --codeshare krapgras/android-biometric-bypass-update-android-11 -U -f <app.package>
``` ```
### **バックグラウンド画像** ### **バックグラウンド画像**
アプリをバックグラウンドにすると、Androidは**アプリケーションのスナップショット**を保存します。アプリがフォアグラウンドに復帰したとき、アプリ本体より先にその画像を読み込むことで、アプリがより速く起動したように見せます。 アプリをバックグラウンドに移動すると、Android はアプリケーションの**スナップショット**を保存します。これにより、フォアグラウンドに復帰したときにアプリ本体より先にその画像を読み込んで、アプリがより速く読み込まれたように見せかけます。
しかし、この**スナップショット**に**機密情報**が含まれている場合、そのスナップショットにアクセスできる第三者が**その情報を盗む**可能性がありますアクセスにはrootが必要な点に注意)。 しかし、このスナップショットに**機密情報**が含まれている場合、スナップショットにアクセスできる者がその情報を**盗む**可能性があります(アクセスするには root が必要である点に注意してください)。
スナップショットは通常次の場所に保存されます: **`/data/system_ce/0/snapshots`** スナップショットは通常次の場所に保存されます **`/data/system_ce/0/snapshots`**
Androidは、レイアウトパラメータFLAG_SECUREを設定することで**スクリーンショットの取得を防止**できます。このフラグを使用すると、ウィンドウの内容がセキュアとして扱われ、スクリーンショットに表示されたり、非セキュアなディスプレイで閲覧されたりするのを防ぎます。 Android は、レイアウトパラメータFLAG_SECURE を設定することで**スクリーンショットのキャプチャを防止する方法**を提供しています。このフラグを使用するとウィンドウの内容がセキュアとして扱われ、スクリーンショットに表示されたり、非セキュアなディスプレイで表示されたりするのを防ぎます。
```bash ```bash
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE); getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
``` ```
### **Android Application Analyzer** ### **Android Application Analyzer**
このツールは dynamic analysis 中に複数のツールを管理するのに役立ちます: [https://github.com/NotSoSecure/android_application_analyzer](https://github.com/NotSoSecure/android_application_analyzer) このツールは動的解析中にさまざまなツールを管理するのに役立ちます: [https://github.com/NotSoSecure/android_application_analyzer](https://github.com/NotSoSecure/android_application_analyzer)
### Intent Injection ### Intent Injection
開発者はしばしば、これらの Intents を処理して `startActivity(...)``sendBroadcast(...)` のようなメソッドに渡す proxy コンポーネントactivities、services、broadcast receivers など)を作成しますが、これは危険を伴う場合があります。 開発者はしばしば activity、service、broadcast receiver のようなプロキシコンポーネントを作成し、これらの Intents を処理して `startActivity(...)``sendBroadcast(...)` のようなメソッドに渡すことがありますが、これはリスクを伴います。
危険は、攻撃者がこれらの Intents を誤誘導して non-exported なアプリコンポーネントをトリガーしたり、機密性の高い content providers にアクセスさせたりできる点にあります。顕著な例として、`WebView` コンポーネントが URL を `Intent` オブジェクトに `Intent.parseUri(...)` を使って変換し、それを実行してしまうことで、悪意ある Intent Injection を引き起こす可能性があります。 危険なのは、攻撃者がこれらの Intents を誤誘導して non-exported なアプリコンポーネントをトリガーしたり、機密性の高い content providers にアクセスしたりできる点です。顕著な例としては、`WebView` コンポーネントが URL を `Intent.parseUri(...)` を介して `Intent` オブジェクトに変換し、それを実行することで悪意のある Intent 注入を引き起こす可能性があります。
### Essential Takeaways ### Essential Takeaways
- **Intent Injection** は web の Open Redirect 問題に似ています。 - **Intent Injection** は web の Open Redirect 問題に似ています。
- エクスプロイトは `Intent` オブジェクトを extras として渡し、それをリダイレクトして安全でない操作を実行させることを含みます。 - エクスプロイトは `Intent` オブジェクトを extras として渡し、それがリダイレクトされて安全でない操作を実行させることを含みます。
- non-exported なコンポーネントや content providers を攻撃者に晒す可能性があります。 - 非エクスポートのコンポーネントや content providers を攻撃者に晒す可能性があります。
- `WebView` の URL `Intent` 変換によって意図しない動作が発生することがあります。 - `WebView` の URL から `Intent` への変換が意図しない動作を引き起こすことがあります。
### Android Client Side Injections and others ### Android クライアントサイドの Injections とその他
おそらく Web でこの種の脆弱性について知っているでしょう。Android アプリケーションでは特に以下の脆弱性に注意する必要があります: おそらく Web でこの種の脆弱性を知っているでしょう。Android アプリケーションではこれらの脆弱性に特に注意する必要があります:
- **SQL Injection:** 動的クエリや Content-Providers を扱うときは、パラメータ化されたクエリを使用していることを確認してください。 - **SQL Injection:** 動的クエリや Content-Providers を扱う場合は、パラメータ化クエリを使用していることを確認してください。
- **JavaScript Injection (XSS):** 任意の WebViews に対して JavaScript と Plugin サポートが無効になっていることを確認してください(デフォルトでは無効)。[More info here](webview-attacks.md#javascript-enabled). - **JavaScript Injection (XSS):** 任意の WebViews では JavaScript と Plugin サポートが無効になっていることを確認してください(デフォルトでは無効)。[より詳しくはこちら](webview-attacks.md#javascript-enabled).
- **Local File Inclusion:** WebViews はファイルシステムへのアクセスを無効にしておくべきです(デフォルトで有効) - `(webview.getSettings().setAllowFileAccess(false);)`. [More info here](webview-attacks.md#javascript-enabled). - **Local File Inclusion:** WebViews はファイルシステムへのアクセスを無効にしておくべきです(デフォルトで有効) - `(webview.getSettings().setAllowFileAccess(false);)`。[より詳しくはこちら](webview-attacks.md#javascript-enabled).
- **Eternal cookies**: 多くのケースで Android アプリがセッションを終了しても cookie が破棄されず、ディスクに保存されることがあります。 - **Eternal cookies**: 多くの場合、Android アプリケーションがセッションを終了しても cookie が取り消されない、あるいはディスクに保存されてしまうことがあります。
- [**Secure Flag** in cookies](../../pentesting-web/hacking-with-cookies/index.html#cookies-flags) - [**Secure Flag** in cookies](../../pentesting-web/hacking-with-cookies/index.html#cookies-flags)
--- ---
## Automatic Analysis ## 自動解析
### [MobSF](https://github.com/MobSF/Mobile-Security-Framework-MobSF) ### [MobSF](https://github.com/MobSF/Mobile-Security-Framework-MobSF)
**Static analysis** **静的解析**
![](<../../images/image (866).png>) ![](<../../images/image (866).png>)
**Vulnerability assessment of the application** を使いやすい web-based frontend で行えます。dynamic analysis も実行できます(ただし環境の準備が必要です)。 **Vulnerability assessment of the application** を使った見やすい web ベースのフロントエンドでの解析。動的解析も実行できます(ただし環境の準備が必要です)。
```bash ```bash
docker pull opensecurity/mobile-security-framework-mobsf docker pull opensecurity/mobile-security-framework-mobsf
docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
@ -650,34 +653,34 @@ exported_activities
services services
receivers receivers
``` ```
**HTTP ツール** **HTTPツール**
When http traffic is capture you can see an ugly view of the captured traffic on "**HTTP(S) Traffic**" bottom or a nicer view in "**Start HTTPTools**" green bottom. From the second option, you can **send** the **captured requests** to **proxies** like Burp or Owasp ZAP.\ HTTPトラフィックをキャプチャすると、"**HTTP(S) Traffic**" ボトムでキャプチャしたトラフィックの見にくい表示が見られるか、"**Start HTTPTools**" の緑色のボタンでより見やすい表示を見ることができます。後者のオプションから、キャプチャしたリクエストを Burp や Owasp ZAP のような **プロキシ****送信** できます。\
To do so, _power on Burp -->_ _turn off Intercept --> in MobSB HTTPTools select the request_ --> press "**Send to Fuzzer**" --> _select the proxy address_ ([http://127.0.0.1:8080\\](http://127.0.0.1:8080)). To do so, _power on Burp -->_ _turn off Intercept --> in MobSB HTTPTools select the request_ --> press "**Send to Fuzzer**" --> _select the proxy address_ ([http://127.0.0.1:8080\\](http://127.0.0.1:8080)).
Once you finish the dynamic analysis with MobSF you can press on "**Start Web API Fuzzer**" to **fuzz http requests** an look for vulnerabilities. 動的解析を MobSF で終えたら、"**Start Web API Fuzzer**" を押して **fuzz http requests** を行い、脆弱性を探すことができます。
> [!TIP] > [!TIP]
> After performing a dynamic analysis with MobSF the proxy settings me be misconfigured and you won't be able to fix them from the GUI. You can fix the proxy settings by doing: > MobSF で動的解析を行った後、プロキシ設定が誤って構成され、GUI から修正できないことがあります。プロキシ設定は以下のように修正できます:
> >
> ``` > ```
> adb shell settings put global http_proxy :0 > adb shell settings put global http_proxy :0
> ``` > ```
### Assisted Dynamic Analysis with Inspeckage ### Inspeckage を使った支援付き動的解析
You can get the tool from [**Inspeckage**](https://github.com/ac-pm/Inspeckage).\ ツールは [**Inspeckage**](https://github.com/ac-pm/Inspeckage) から入手できます。\
このツールはいくつかの **Hooks** を使用して、**dynamic analysis** を行っている間にアプリケーション内で**何が起きているか**を把握できるようにします。 このツールはいくつかの **Hooks** を使用して、**動的解析** を行っている間にアプリケーション内で**何が起きているか**を知らせてくれます。
### [Yaazhini](https://www.vegabird.com/yaazhini/) ### [Yaazhini](https://www.vegabird.com/yaazhini/)
これは **GUI を使った static analysis を実行するのに優れたツール** です これは **GUI で静的解析を行うための優れたツール** です
![](<../../images/image (741).png>) ![](<../../images/image (741).png>)
### [Qark](https://github.com/linkedin/qark) ### [Qark](https://github.com/linkedin/qark)
This tool is designed to look for several **security related Android application vulnerabilities**, either in **source code** or **packaged APKs**. The tool is also **capable of creating a "Proof-of-Concept" deployable APK** and **ADB commands**, to exploit some of the found vulnerabilities (Exposed activities, intents, tapjacking...). As with Drozer, there is no need to root the test device. このツールは、**セキュリティ関連の Android アプリケーション脆弱性** を、**ソースコード** または **packaged APKs** のいずれかで検出するように設計されています。さらに、このツールは発見した脆弱性Exposed activities、intents、tapjacking...)を悪用するための "Proof-of-Concept" なデプロイ可能な APK と **ADB commands** を作成することができます。Drozer と同様に、テストデバイスを root 化する必要はありません。
```bash ```bash
pip3 install --user qark # --user is only needed if not using a virtualenv pip3 install --user qark # --user is only needed if not using a virtualenv
qark --apk path/to/my.apk qark --apk path/to/my.apk
@ -686,22 +689,22 @@ qark --java path/to/specific/java/file.java
``` ```
### [**ReverseAPK**](https://github.com/1N3/ReverseAPK.git) ### [**ReverseAPK**](https://github.com/1N3/ReverseAPK.git)
- 参照しやすいように抽出されたすべてのファイルを表示す - 参照しやすいように抽出されたすべてのファイルを表示しま
- APKファイルを自動的にJavaおよびSmali形式にデコンパイルす - APKファイルを自動的にJavaおよびSmali形式にデコンパイルしま
- AndroidManifest.xmlを分析して一般的な脆弱性や挙動を検出する - 一般的な脆弱性や挙動についてAndroidManifest.xmlを解析します
- 静的ソースコード解析により一般的な脆弱性や挙動を検出す - 静的ソースコード解析により一般的な脆弱性や挙動を検出しま
- デバイス情報を表示する - デバイス情報
- など - その他多数
```bash ```bash
reverse-apk relative/path/to/APP.apk reverse-apk relative/path/to/APP.apk
``` ```
### [SUPER Android Analyzer](https://github.com/SUPERAndroidAnalyzer/super) ### [SUPER Android Analyzer](https://github.com/SUPERAndroidAnalyzer/super)
SUPERはWindows、MacOS X、Linuxで使用できるコマンドラインアプリケーションで、_.apk_ ファイルを解析して脆弱性を検出します。これはAPKsを解凍し、複数のルールを適用して脆弱性を検出することで行います。 SUPER は Windows、MacOS X、Linux で利用できるコマンドラインアプリケーションで、_.apk_ ファイルを解析して脆弱性を検出します。APK を展開し、一連のルールを適用して脆弱性を見つけます。
すべてのルールは `rules.json` ファイルに集約されており、各企業やテスターは必要に応じて独自のルールを作成して解析できます。 すべてのルールは `rules.json` ファイルに集約されており、各企業やテスターは必要に応じて独自のルールを作成できます。
最新のバイナリは[download page](https://superanalyzer.rocks/download.html)からダウンロードしてください。 最新のバイナリは [download page](https://superanalyzer.rocks/download.html) からダウンロードしてください。
``` ```
super-analyzer {apk_file} super-analyzer {apk_file}
``` ```
@ -709,17 +712,17 @@ super-analyzer {apk_file}
![](<../../images/image (297).png>) ![](<../../images/image (297).png>)
StaCoAnは、モバイルアプリケーションの[static code analysis](https://en.wikipedia.org/wiki/Static_program_analysis)を行う開発者、bugbounty hunters、ethical hackersを支援する**クロスプラットフォーム**ツールです。 StaCoAn は、モバイルアプリケーションに対して [static code analysis](https://en.wikipedia.org/wiki/Static_program_analysis) を行う開発者、bugbounty hunters、ethical hackers を支援する**クロスプラットフォーム**ツールです。
使い方は、モバイルアプリのファイル(.apk または .ipa ファイル)を StaCoAn アプリにドラッグ&ドロップすると、視覚的で持ち運び可能なレポートを自動生成するというものです。設定や wordlists を調整してカスタマイズした出力にできます。 コンセプトは、モバイルアプリケーションファイル(.apk または .ipa ファイル)を StaCoAn アプリケーションにドラッグアンドドロップすると、視覚的で持ち運び可能なレポートを生成するというものです。設定や wordlists を調整して、カスタマイズされた体験を得ることができます。
ダウンロード[ latest release](https://github.com/vincentcox/StaCoAn/releases): Download[ latest release](https://github.com/vincentcox/StaCoAn/releases):
``` ```
./stacoan ./stacoan
``` ```
### [AndroBugs](https://github.com/AndroBugs/AndroBugs_Framework) ### [AndroBugs](https://github.com/AndroBugs/AndroBugs_Framework)
AndroBugs Framework は、Android 脆弱性解析システムで、開発者や hackers が Android アプリケーションの潜在的なセキュリティ脆弱性を発見するのを支援します。\ AndroBugs Framework は、開発者や hackers が Android アプリケーションの潜在的なセキュリティ脆弱性を発見するのに役立つ脆弱性解析システムです.\
[Windows releases](https://github.com/AndroBugs/AndroBugs_Framework/releases) [Windows releases](https://github.com/AndroBugs/AndroBugs_Framework/releases)
``` ```
python androbugs.py -f [APK file] python androbugs.py -f [APK file]
@ -727,11 +730,11 @@ androbugs.exe -f [APK file]
``` ```
### [Androwarn](https://github.com/maaaaz/androwarn) ### [Androwarn](https://github.com/maaaaz/androwarn)
**Androwarn** は、Android アプリケーションによって開発された潜在的な悪意ある振る舞いを検出し、ユーザーに警告することを主目的としたツールです。 **Androwarn** は、Android アプリケーションによって発生する可能性のある悪意のある振る舞いを検出し、ユーザーに警告することを主目的としたツールです。
検出は、アプリケーションの Dalvik bytecode を **Smali** として表現したものに対する **static analysis**[`androguard`](https://github.com/androguard/androguard) ライブラリで行うことで実行されます。 検出は、[`androguard`](https://github.com/androguard/androguard) ライブラリを用いて、アプリケーションの Dalvik bytecode**Smali** 表現)に対する **static analysis** により行われます。
このツールは、次のような **common behavior of "bad" applications** を検出します: Telephony identifiers exfiltration, Audio/video flow interception, PIM data modification, Arbitrary code execution... このツールは、**悪意のあるアプリケーションの一般的な挙動**Telephony identifiers exfiltration、Audio/video flow interception、PIM data modification、Arbitrary code execution...)を検出します。
``` ```
python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3 python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3
``` ```
@ -739,7 +742,7 @@ python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3
![](<../../images/image (595).png>) ![](<../../images/image (595).png>)
**MARA** is a **M**obile **A**pplication **R**everse engineering and **A**nalysis Framework. モバイルアプリの一般的に使用される reverse engineering と analysis ツールをまとめ、OWASP mobile security threats に対するモバイルアプリのテストを支援するツールです。目的は、この作業をモバイルアプリ開発者やセキュリティ専門家にとってより簡単で扱いやすくすることです。 **MARA** は **M**obile **A**pplication **R**everse engineering and **A**nalysis Framework の略です。一般的に使用されるモバイルアプリのリバースエンジニアリングおよび解析ツールをまとめたツールで、モバイルアプリを OWASP のモバイルセキュリティ脅威に対してテストするのを支援します。目的は、モバイルアプリ開発者やセキュリティ専門家にとってこの作業をより簡単かつ扱いやすくすることです。
It is able to: It is able to:
@ -752,7 +755,7 @@ It is able to:
### Koodous ### Koodous
Useful to detect malware: [https://koodous.com/](https://koodous.com/) malware を検出するのに有用: [https://koodous.com/](https://koodous.com/)
## Obfuscating/Deobfuscating code ## Obfuscating/Deobfuscating code
@ -760,7 +763,7 @@ Note that depending the service and configuration you use to obfuscate the code.
### [ProGuard](<https://en.wikipedia.org/wiki/ProGuard_(software)>) ### [ProGuard](<https://en.wikipedia.org/wiki/ProGuard_(software)>)
From [Wikipedia](<https://en.wikipedia.org/wiki/ProGuard_(software)>): **ProGuard** is an open source command-line tool that shrinks, optimizes and obfuscates Java code. Java コードを縮小・最適化し、obfuscates するオープンソースのコマンドラインツールです。bytecode の最適化や未使用命令の検出と削除が可能です。ProGuard はフリーソフトウェアで、GNU General Public License, version 2 の下で配布されています。 From [Wikipedia](<https://en.wikipedia.org/wiki/ProGuard_(software)>): **ProGuard** is an open source command-line tool that shrinks, optimizes and obfuscates Java code. It is able to optimize bytecode as well as detect and remove unused instructions. ProGuard is free software and is distributed under the GNU General Public License, version 2.
ProGuard is distributed as part of the Android SDK and runs when building the application in release mode. ProGuard is distributed as part of the Android SDK and runs when building the application in release mode.
@ -780,7 +783,7 @@ Find a step-by-step guide to deobfuscate the apk in [https://blog.lexfo.fr/dexgu
**DeGuard reverses the process of obfuscation performed by Android obfuscation tools. This enables numerous security analyses, including code inspection and predicting libraries.** **DeGuard reverses the process of obfuscation performed by Android obfuscation tools. This enables numerous security analyses, including code inspection and predicting libraries.**
obfuscated APK を彼らのプラットフォームにアップロードできます。 You can upload an obfuscated APK to their platform.
### [Deobfuscate android App]https://github.com/In3tinct/deobfuscate-android-app ### [Deobfuscate android App]https://github.com/In3tinct/deobfuscate-android-app
@ -802,19 +805,20 @@ APKiD gives you information about **how an APK was made**. It identifies many **
### [Androl4b](https://github.com/sh4hin/Androl4b) ### [Androl4b](https://github.com/sh4hin/Androl4b)
AndroL4b は ubuntu-mate ベースの Android security virtual machine で、reverse engineering と malware analysis のために様々な研究者や開発者から集められた最新のフレームワーク、チュートリアル、lab を含んでいます。 AndroL4b は ubuntu-mate ベースの Android セキュリティ仮想マシンで、リバースエンジニアリングおよび malware 分析のための最新フレームワーク、チュートリアル、ラボを様々なセキュリティ研究者や研究家から集めたコレクションを含みます。
## References ## References
- [https://owasp.org/www-project-mobile-app-security/](https://owasp.org/www-project-mobile-app-security/) - [https://owasp.org/www-project-mobile-app-security/](https://owasp.org/www-project-mobile-app-security/)
- [https://appsecwiki.com/#/](https://appsecwiki.com/#/) 優れたリソース一覧です - [https://appsecwiki.com/#/](https://appsecwiki.com/#/) 素晴らしいリソースの一覧です
- [https://maddiestone.github.io/AndroidAppRE/](https://maddiestone.github.io/AndroidAppRE/) Android quick course - [https://maddiestone.github.io/AndroidAppRE/](https://maddiestone.github.io/AndroidAppRE/) Android quick course
- [https://manifestsecurity.com/android-application-security/](https://manifestsecurity.com/android-application-security/) - [https://manifestsecurity.com/android-application-security/](https://manifestsecurity.com/android-application-security/)
- [https://github.com/Ralireza/Android-Security-Teryaagh](https://github.com/Ralireza/Android-Security-Teryaagh) - [https://github.com/Ralireza/Android-Security-Teryaagh](https://github.com/Ralireza/Android-Security-Teryaagh)
- [https://www.youtube.com/watch?v=PMKnPaGWxtg\&feature=youtu.be\&ab_channel=B3nacSec](https://www.youtube.com/watch?v=PMKnPaGWxtg&feature=youtu.be&ab_channel=B3nacSec) - [https://www.youtube.com/watch?v=PMKnPaGWxtg\&feature=youtu.be\&ab_channel=B3nacSec](https://www.youtube.com/watch?v=PMKnPaGWxtg&feature=youtu.be&ab_channel=B3nacSec)
- [SSLPinDetect: Advanced SSL Pinning Detection for Android Security Analysis](https://petruknisme.medium.com/sslpindetect-advanced-ssl-pinning-detection-for-android-security-analysis-1390e9eca097) - [SSLPinDetect: Advanced SSL Pinning Detection for Android Security Analysis](https://petruknisme.medium.com/sslpindetect-advanced-sslpinning-detection-for-android-security-analysis-1390e9eca097)
- [SSLPinDetect GitHub](https://github.com/aancw/SSLPinDetect) - [SSLPinDetect GitHub](https://github.com/aancw/SSLPinDetect)
- [smali-sslpin-patterns](https://github.com/aancw/smali-sslpin-patterns) - [smali-sslpin-patterns](https://github.com/aancw/smali-sslpin-patterns)
- [Build a Repeatable Android Bug Bounty Lab: Emulator vs Magisk, Burp, Frida, and Medusa](https://www.yeswehack.com/learn-bug-bounty/android-lab-mobile-hacking-tools)
## Yet to try ## Yet to try

View File

@ -2,55 +2,72 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
このページは、instrumentation を検出/ブロックしたり TLS pinning を強制する Android アプリに対して、動的解析を取り戻すための実践的なワークフローを提供します。高速なトリアージ、一般的な検出方法、可能な限り再パッケージ不要で回避するためのコピペ可能なフック/戦術に焦点を当てています。 このページは、instrumentation を検出root ブロックする、もしくは TLS pinning を強制する Android アプリに対して、動的解析dynamic analysisを取り戻すための実践的なワークフローを提供します。迅速なトリアージ、一般的な検出方法、そして可能な限りリパッキングせずにバイパスするためのコピペ可能なフック/戦術に焦点を当てています。
## Detection Surface (what apps check) ## Detection Surface (what apps check)
- Root チェック: su binary、Magisk paths、getprop values、一般的な root パッケージ - Root チェック: su バイナリ、Magisk パス、getprop 値、一般的な root パッケージ
- Frida/debugger チェック (Java): Debug.isDebuggerConnected(), ActivityManager.getRunningAppProcesses(), getRunningServices(), /proc のスキャン、classpath、読み込まれた libs - Frida/debugger チェック (Java): Debug.isDebuggerConnected(), ActivityManager.getRunningAppProcesses(), getRunningServices(), /proc のスキャン、classpath、読み込まれた libs
- Native antidebug: ptrace(), syscalls、antiattach、ブレークポイント、インラインフック - ネイティブ antidebug: ptrace(), syscalls、antiattach、ブレークポイント、インラインフック
- Early init チェック: Application.onCreate() やプロセス開始時のフックで、instrumentation が存在するとクラッシュさせるもの - 早期初期化チェック: Application.onCreate() や、instrumentation が存在するとクラッシュするプロセス開始フック
- TLS pinning: custom TrustManager/HostnameVerifier、OkHttp CertificatePinner、Conscrypt pinning、ネイティブのピン - TLS pinning: カスタム TrustManager/HostnameVerifier、OkHttp CertificatePinner、Conscrypt pinning、ネイティブ pin
## Step 1 — Quick win: hide root with Magisk DenyList ## Step 1 — Quick win: hide root with Magisk DenyList
- Magisk で Zygisk を有効にする - Magisk で Zygisk を有効
- DenyList を有効にし、対象パッケージを追加する - DenyList を有効化し、ターゲットパッケージを追加
- 再起動して再テストする - 再起動して再テスト
多くのアプリは明白な指標su/Magisk paths/getpropのみをチェックします。DenyList はこうした単純なチェックを無効化することが多いです。 多くのアプリは明らかな指標su/Magisk パス/getpropしか確認していません。DenyList はナイーブなチェックを無効化することが多いです。
References: References:
- Magisk (Zygisk & DenyList): https://github.com/topjohnwu/Magisk - Magisk (Zygisk & DenyList): https://github.com/topjohnwu/Magisk
## Step 2 — 30second Frida Codeshare tests ## Step 2 — 30second Frida Codeshare tests
深掘りする前に、よく使われるドロップインスクリプトを試してください: 深掘りする前に一般的なドロップインスクリプトを試してください:
- anti-root-bypass.js - anti-root-bypass.js
- anti-frida-detection.js - anti-frida-detection.js
- hide_frida_gum.js - hide_frida_gum.js
: Example:
```bash ```bash
frida -U -f com.example.app -l anti-frida-detection.js frida -U -f com.example.app -l anti-frida-detection.js
``` ```
これらは通常、Java の root/debug チェック、process/service スキャン、およびネイティブ ptrace() をスタブ化します。軽度に保護されたアプリには有用ですが、ハード化されたターゲットでは専用のフックが必要になる場合があります。 これらは通常、Java の root/debug チェック、プロセス/サービスのスキャン、およびネイティブの ptrace() をスタブ化します。軽度に保護されたアプリでは有用ですが、強化されたターゲットではカスタムのフックが必要な場合があります。
- Codeshare: https://codeshare.frida.re/ - Codeshare: https://codeshare.frida.re/
## ステップ3 — init-time detectors を遅れてアタッチして回避する ## MedusaFrida フレームワーク)で自動化
多くの検出は process spawn/onCreate() の実行時のみ走ります。Spawntime injection (-f) や gadgets は検出されやすいですが、UI がロードされた後にアタッチすれば回避できることがあります。 Medusa は、SSL unpinning、root/emulator detection bypass、HTTP comms logging、crypto key interception などの 90+ の既成モジュールを提供します。
```bash
git clone https://github.com/Ch0pin/medusa
cd medusa
pip install -r requirements.txt
python medusa.py
# Example interactive workflow
show categories
use http_communications/multiple_unpinner
use root_detection/universal_root_detection_bypass
run com.target.app
```
ヒント: Medusa はカスタム hooks を作る前の素早い成果に最適です。必要な modules を選んで自分の scripts と組み合わせることもできます。
## Step 3 — init-time detectors を回避するには遅めに attach する
多くの検知は process spawn/onCreate() の間にのみ実行されます。Spawntime injection (-f) や gadgets は検出されやすく、UI が読み込まれた後に attach するとすり抜けられることがあります。
```bash ```bash
# Launch the app normally (launcher/adb), wait for UI, then attach # Launch the app normally (launcher/adb), wait for UI, then attach
frida -U -n com.example.app frida -U -n com.example.app
# Or with Objection to attach to running process # Or with Objection to attach to running process
aobjection --gadget com.example.app explore # if using gadget aobjection --gadget com.example.app explore # if using gadget
``` ```
If this works, keep the session stable and proceed to map and stub checks. これで動作する場合は、セッションを安定させたまま map and stub checks に進んでください。
## Step 4 — Jadx と文字列探索で検出ロジックをマッピング ## Step 4 — Jadx と string hunting による検出ロジックのマッピング
Static triage keywords in Jadx: Static triage keywords in Jadx:
- "frida", "gum", "root", "magisk", "ptrace", "su", "getprop", "debugger" - "frida", "gum", "root", "magisk", "ptrace", "su", "getprop", "debugger"
@ -61,16 +78,16 @@ public boolean isFridaDetected() {
return getRunningServices().contains("frida"); return getRunningServices().contains("frida");
} }
``` ```
確認・フックすべき一般的なAPI: 確認/ hook する一般的なAPI:
- android.os.Debug.isDebuggerConnected - android.os.Debug.isDebuggerConnected
- android.app.ActivityManager.getRunningAppProcesses / getRunningServices - android.app.ActivityManager.getRunningAppProcesses / getRunningServices
- java.lang.System.loadLibrary / System.load (native bridge) - java.lang.System.loadLibrary / System.load (native bridge)
- java.lang.Runtime.exec / ProcessBuilder (probing commands) - java.lang.Runtime.exec / ProcessBuilder (probing commands)
- android.os.SystemProperties.get (root/emulator heuristics) - android.os.SystemProperties.get (root/emulator heuristics)
## ステップ5 — Frida (Java) によるランタイムのスタブ化 ## ステップ5 — Runtime stubbing with Frida (Java)
カスタムガードをオーバーライドして、再パッケージ化せずに安全な値を返す: カスタムガードをオーバーライドして、repacking なしで安全な値を返す:
```js ```js
Java.perform(() => { Java.perform(() => {
const Checks = Java.use('com.example.security.Checks'); const Checks = Java.use('com.example.security.Checks');
@ -85,7 +102,7 @@ const AM = Java.use('android.app.ActivityManager');
AM.getRunningAppProcesses.implementation = function () { return java.util.Collections.emptyList(); }; AM.getRunningAppProcesses.implementation = function () { return java.util.Collections.emptyList(); };
}); });
``` ```
初期の crashes をトリアージしていますか?終了直前に Dump classes を行い、検出に使われそうな namespaces を特定しましょう: 初期のクラッシュをトリアージしていますか?終了直前に Dump classes を取得し、検出の可能性の高い namespaces を特定します:
```js ```js
Java.perform(() => { Java.perform(() => {
Java.enumerateLoadedClasses({ Java.enumerateLoadedClasses({
@ -94,7 +111,17 @@ onComplete: () => console.log('Done')
}); });
}); });
``` ```
実行フローを確認するために、疑わしいメソッドをログ出力して無効化する: ```javascript
// Quick root detection stub example (adapt to target package/class names)
Java.perform(() => {
try {
const RootChecker = Java.use('com.target.security.RootCheck');
RootChecker.isDeviceRooted.implementation = function () { return false; };
} catch (e) {}
});
```
疑わしいメソッドをログ出力して無効化し、実行フローを確認する:
```js ```js
Java.perform(() => { Java.perform(() => {
const Det = Java.use('com.example.security.DetectionManager'); const Det = Java.use('com.example.security.DetectionManager');
@ -104,9 +131,49 @@ return false;
}; };
}); });
``` ```
## ステップ6 — Java hooksが失敗した場合はJNI/nativeの経路をたどる ## Bypass emulator/VM detection (Java stubs)
JNIのエントリポイントをトレースして、native loadersとdetection initを特定する: 一般的なヒューリスティック: Build.FINGERPRINT/MODEL/MANUFACTURER/HARDWARE に generic/goldfish/ranchu/sdk が含まれる; QEMU のアーティファクト(/dev/qemu_pipe, /dev/socket/qemud; デフォルト MAC 02:00:00:00:00:00; 10.0.2.x の NAT; telephony/sensors が欠如している。
Build フィールドの簡易な偽装例:
```js
Java.perform(function(){
var Build = Java.use('android.os.Build');
Build.MODEL.value = 'Pixel 7 Pro';
Build.MANUFACTURER.value = 'Google';
Build.BRAND.value = 'google';
Build.FINGERPRINT.value = 'google/panther/panther:14/UP1A.231105.003/1234567:user/release-keys';
});
```
ファイル存在チェックや識別子TelephonyManager.getDeviceId/SubscriberId、WifiInfo.getMacAddress、SensorManager.getSensorList用のスタブを追加し、現実的な値を返すようにしてください。
## SSL pinning bypass quick hook (Java)
カスタムTrustManagersを無効化し、許容的なSSL contextsを強制する:
```js
Java.perform(function(){
var X509TrustManager = Java.use('javax.net.ssl.X509TrustManager');
var SSLContext = Java.use('javax.net.ssl.SSLContext');
// No-op validations
X509TrustManager.checkClientTrusted.implementation = function(){ };
X509TrustManager.checkServerTrusted.implementation = function(){ };
// Force permissive TrustManagers
var TrustManagers = [ X509TrustManager.$new() ];
var SSLContextInit = SSLContext.init.overload('[Ljavax.net.ssl.KeyManager;','[Ljavax.net.ssl.TrustManager;','java.security.SecureRandom');
SSLContextInit.implementation = function(km, tm, sr){
return SSLContextInit.call(this, km, TrustManagers, sr);
};
});
```
注意
- OkHttp 用に拡張する: 必要に応じて okhttp3.CertificatePinner と HostnameVerifier を hook するか、CodeShare の universal unpinning script を使用する。
- 実行例: `frida -U -f com.target.app -l ssl-bypass.js --no-pause`
## Step 6 — Java hooks が失敗した場合は JNI/native のトレイルを追う
JNI エントリポイントをトレースして native loaders と detection init を特定する:
```bash ```bash
frida-trace -n com.example.app -i "JNI_OnLoad" frida-trace -n com.example.app -i "JNI_OnLoad"
``` ```
@ -117,7 +184,7 @@ nm -D libfoo.so | head
objdump -T libfoo.so | grep Java_ objdump -T libfoo.so | grep Java_
strings -n 6 libfoo.so | egrep -i 'frida|ptrace|gum|magisk|su|root' strings -n 6 libfoo.so | egrep -i 'frida|ptrace|gum|magisk|su|root'
``` ```
Interactive/native reversing: インタラクティブ/ネイティブ reversing:
- Ghidra: https://ghidra-sre.org/ - Ghidra: https://ghidra-sre.org/
- r2frida: https://github.com/nowsecure/r2frida - r2frida: https://github.com/nowsecure/r2frida
@ -135,28 +202,30 @@ return -1; // pretend failure
reversing-native-libraries.md reversing-native-libraries.md
{{#endref}} {{#endref}}
## ステップ7 — Objection patching (embed gadget / strip basics) ## ステップ 7 — Objection patching (embed gadget / strip basics)
repackingをruntime hooksの代わりに好む場合は、次を試してください: runtime hooks より repacking を好む場合は、次を試してください:
```bash ```bash
objection patchapk --source app.apk objection patchapk --source app.apk
``` ```
注記: Notes:
- Requires apktool; ensure a current version from the official guide to avoid build issues: https://apktool.org/docs/install - apktool が必要です。ビルドの問題を避けるため、公式ガイドの最新バージョンを確認してください: https://apktool.org/docs/install
- Gadget injection enables instrumentation without root but can still be caught by stronger inittime checks. - Gadget injection は root なしで instrumentation を可能にしますが、より強力な inittime checks によって検出される可能性があります。
参考: Optionally, add LSPosed modules and Shamiko for stronger root hiding in Zygisk environments, and curate DenyList to cover child processes.
References:
- Objection: https://github.com/sensepost/objection - Objection: https://github.com/sensepost/objection
## Step 8 — フォールバック: ネットワーク可視化のために TLS pinning をパッチする ## Step 8 — Fallback: Patch TLS pinning for network visibility
もし instrumentation がブロックされている場合、pinning を静的に除去することでトラフィックを確認できます: If instrumentation is blocked, you can still inspect traffic by removing pinning statically:
```bash ```bash
apk-mitm app.apk apk-mitm app.apk
# Then install the patched APK and proxy via Burp/mitmproxy # Then install the patched APK and proxy via Burp/mitmproxy
``` ```
- ツール: https://github.com/shroudedcode/apk-mitm - ツール: https://github.com/shroudedcode/apk-mitm
- ネットワーク設定の CAtrust トリック(および Android 7+ user CA trustについては、次を参照 - ネットワーク構成の CAtrust トリック(および Android 7+ user CA trustについては、次を参照:
{{#ref}} {{#ref}}
make-apk-accept-ca-certificate.md make-apk-accept-ca-certificate.md
@ -186,12 +255,12 @@ apk-mitm app.apk
``` ```
## ヒントと注意点 ## ヒントと注意点
- アプリが起動時にクラッシュする場合は、spawnより遅くattachすることを優先する - アプリが起動時にクラッシュする場合は、spawn させるより late attaching を遅らせて attach する方が望ましい
- いくつかの検知は重要なフロー(例: payment、authで再実行されることがある — ナビゲーション中はhooksを有効に保つ - 一部の detections は重要なフローpayment、authで再実行される — navigation 中は hooks を有効に保つ
- 静的解析と動的解析を組み合わせる: Jadxで文字列を探索してクラスを絞り、ランタイムで確認するためにメソッドをhookする - static と dynamic を組み合わせる: Jadx で string hunt をして候補クラスを絞り、runtime でメソッドを hook して検証する
- 強化されたアプリはpackersやnative TLS pinningを使用する可能性がある — ネイティブコードの逆解析を想定する - Hardened apps は packers や native TLS pinning を使う場合がある — native code をリバースすることを想定する
## 参考 ## References
- [Reversing Android Apps: Bypassing Detection Like a Pro](https://www.kayssel.com/newsletter/issue-12/) - [Reversing Android Apps: Bypassing Detection Like a Pro](https://www.kayssel.com/newsletter/issue-12/)
- [Frida Codeshare](https://codeshare.frida.re/) - [Frida Codeshare](https://codeshare.frida.re/)
@ -202,5 +271,7 @@ apk-mitm app.apk
- [r2frida](https://github.com/nowsecure/r2frida) - [r2frida](https://github.com/nowsecure/r2frida)
- [Apktool install guide](https://apktool.org/docs/install) - [Apktool install guide](https://apktool.org/docs/install)
- [Magisk](https://github.com/topjohnwu/Magisk) - [Magisk](https://github.com/topjohnwu/Magisk)
- [Medusa (Android Frida framework)](https://github.com/Ch0pin/medusa)
- [Build a Repeatable Android Bug Bounty Lab: Emulator vs Magisk, Burp, Frida, and Medusa](https://www.yeswehack.com/learn-bug-bounty/android-lab-mobile-hacking-tools)
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,33 +2,33 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
このコンテンツの作成中に助けてくれた[**@offsecjay**](https://twitter.com/offsecjay)に感謝します。 このコンテンツ作成にあたりご協力いただいた [**@offsecjay**](https://twitter.com/offsecjay) 深く感謝します。
## What is ## 概要
Android Studioは、**APKをテストするために使用できるAndroidの仮想マシンを実行することを可能にします**。これらを使用するには、次のものが必要です: Android Studio により、**APKs のテストに使用できる Android の仮想マシンを実行**できます。使用するには次が必要です:
- **Android SDKツール** - [ここからダウンロード](https://developer.android.com/studio/releases/sdk-tools)。 - **Android SDK tools** - [Download here](https://developer.android.com/studio/releases/sdk-tools).
- または**Android Studio**Android SDKツール付き - [ここからダウンロード](https://developer.android.com/studio)。 - または **Android Studio**Android SDK tools を含む) - [Download here](https://developer.android.com/studio).
Windowsでは(私の場合)、**Android Studioをインストールした後**、**SDKツールは**次の場所にインストールされました:`C:\Users\<UserName>\AppData\Local\Android\Sdk\tools` Windows(私の場合)では、**Android Studio をインストールした後**、**SDK Tools がインストールされていた場所**: `C:\Users\<UserName>\AppData\Local\Android\Sdk\tools`
Macでは、**SDKツールをダウンロード**し、次のコマンドを実行してPATHに追加できます mac では、**SDK tools をダウンロード**して、次のコマンドで PATH に追加できます:
```bash ```bash
brew tap homebrew/cask brew tap homebrew/cask
brew install --cask android-sdk brew install --cask android-sdk
``` ```
**Android Studio GUI**から、[https://stackoverflow.com/questions/46402772/failed-to-install-android-sdk-java-lang-noclassdeffounderror-javax-xml-bind-a](https://stackoverflow.com/questions/46402772/failed-to-install-android-sdk-java-lang-noclassdeffounderror-javax-xml-bind-a)に示されているように、`~/Library/Android/sdk/cmdline-tools/latest/bin/``~/Library/Android/sdk/platform-tools/`、および`~/Library/Android/sdk/emulator/`にインストールされます。 または **Android Studio GUI** から([https://stackoverflow.com/questions/46402772/failed-to-install-android-sdk-java-lang-noclassdeffounderror-javax-xml-bind-a](https://stackoverflow.com/questions/46402772/failed-to-install-android-sdk-java-lang-noclassdeffounderror-javax-xml-bind-a) に示されているように)これにより `~/Library/Android/sdk/cmdline-tools/latest/bin/``~/Library/Android/sdk/platform-tools/``~/Library/Android/sdk/emulator/` にインストールされます
Javaの問題について: Java の問題について:
```java ```java
export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jbr/Contents/Home export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jbr/Contents/Home
``` ```
## GUI ## GUI
### 仮想マシンの準備 ### Prepare Virtual Machine
Android Studioをインストールした場合は、メインプロジェクトビューを開いて、_**ツール**_ --> _**AVDマネージャー**_にアクセスできます。 Android Studioをインストールしている場合、メインのプロジェクトビューを開き、次を選択できます: _**Tools**_ --> _**AVD Manager.**_
<div align="center" data-full-width="false"> <div align="center" data-full-width="false">
@ -36,38 +36,36 @@ Android Studioをインストールした場合は、メインプロジェクト
</div> </div>
次に、_**仮想デバイスの作成**_をクリックします。 次に、_**Create Virtual Device**_ をクリックします
<figure><img src="../../images/image (1143).png" alt="" width="188"><figcaption></figcaption></figure> <figure><img src="../../images/image (1143).png" alt="" width="188"><figcaption></figcaption></figure>
_**使用したい電話を選択**_し、_**次へ**_をクリックします。 _**select**_ したい端末を選び、_**Next.**_ をクリックします。
> [!WARNING] > [!WARNING]
> Play Storeがインストールされた電話が必要な場合は、Play Storeアイコンのあるものを選択してください! > Play Storeがインストールされた端末が必要な場合は、Play Storeアイコンが付いているものを選択してください!
> >
> <img src="../../images/image (1144).png" alt="" data-size="original"> > <img src="../../images/image (1144).png" alt="" data-size="original">
現在のビューでは、電話が実行する**Androidイメージを選択してダウンロード**できます: 現在のビューでは、端末が実行するAndroidイメージを**選択してダウンロード**できます:
<figure><img src="../../images/image (1145).png" alt="" width="375"><figcaption></figcaption></figure> <figure><img src="../../images/image (1145).png" alt="" width="375"><figcaption></figcaption></figure>
それを選択し、ダウンロードされていない場合は、名前の横にある_**ダウンロード**_シンボルをクリックします**今はイメージがダウンロードされるまで待ってください)。**\ それを選択し、まだダウンロードされていない場合は名前の横にある_**Download**_シンボルをクリックしてくださいイメージのダウンロードが完了するまで待ちます。**`Next`** と **`Finish`** を選択してください。\
イメージがダウンロードされたら、**`次へ`**と**`完了`**を選択します。 イメージがダウンロードされると仮想マシンが作成されます。以後、AVD managerにアクセスするたびにその仮想マシンが表示されます。
仮想マシンが作成されます。これで、**AVDマネージャーにアクセスするたびにそれが表示されます**。 ### Run Virtual Machine
### 仮想マシンの実行 実行するには、_**Start button**_ を押します。
**実行**するには、_**スタートボタン**_を押します。
![](<../../images/image (518).png>) ![](<../../images/image (518).png>)
## コマンドラインツール ## Command Line tool
> [!WARNING] > [!WARNING]
> macOSの場合、`avdmanager`ツールは`/Users/<username>/Library/Android/sdk/tools/bin/avdmanager`に、`emulator``/Users/<username>/Library/Android/sdk/emulator/emulator`にあります。インストールされている場合です > macOSでは、`avdmanager` ツールは `/Users/<username>/Library/Android/sdk/tools/bin/avdmanager` に、`emulator` `/Users/<username>/Library/Android/sdk/emulator/emulator` にあります(インストールされている場合)
まず、**使用したい電話を決定する必要があります**。可能な電話のリストを見るには、次のコマンドを実行します: まず、どの端末を使うか**決める必要があります**。使用可能な端末の一覧を表示するには、次を実行してください:
``` ```
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\avdmanager.bat list device C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\avdmanager.bat list device
@ -95,16 +93,16 @@ Name: Nexus 10
OEM : Google OEM : Google
[...] [...]
``` ```
デバイスの名前を決定したら、**このデバイスで実行するAndroidイメージを決定する必要があります。**\ 使用するデバイスの名前を決めたら、次に**そのデバイスで実行する Android イメージを決める必要があります。**\
`sdkmanager`を使用してすべてのオプションをリストできます: すべてのオプションは `sdkmanager` を使って一覧表示できます:
```bash ```bash
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\sdkmanager.bat --list C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\sdkmanager.bat --list
``` ```
そして、使用したいもの(またはすべて)を**ダウンロード**します: そして、使用したいもの(またはすべて)を**ダウンロード**するには、次のコマンドを使用してください:
```bash ```bash
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\sdkmanager.bat "platforms;android-28" "system-images;android-28;google_apis;x86_64" C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\sdkmanager.bat "platforms;android-28" "system-images;android-28;google_apis;x86_64"
``` ```
ダウンロードしたいAndroidイメージをダウンロードしたら、次のコマンドで**ダウンロードしたすべてのAndroidイメージをリスト**できます: 使用したい Android image をダウンロードしたら、次のコマンドで **ダウンロード済みの Android images をすべて一覧表示** できます:
``` ```
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\avdmanager.bat list target C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\avdmanager.bat list target
---------- ----------
@ -120,12 +118,12 @@ Type: Platform
API level: 29 API level: 29
Revision: 4 Revision: 4
``` ```
この時点で、使用したいデバイスを決定し、Androidイメージをダウンロードしたので、**次のコマンドを使用して仮想マシンを作成できます**: この時点で、使用するデバイスを決め、Androidイメージをダウンロードしているので、**仮想マシンを作成するには次の方法を使用できます**:
```bash ```bash
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\avdmanager.bat -v create avd -k "system-images;android-28;google_apis;x86_64" -n "AVD9" -d "Nexus 5X" C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\avdmanager.bat -v create avd -k "system-images;android-28;google_apis;x86_64" -n "AVD9" -d "Nexus 5X"
``` ```
最後のコマンドで、**"_AVD9_"という名前のVMを作成しました**。使用した**デバイス**は"_Nexus 5X_"で、**Androidイメージ**は"_system-images;android-28;google_apis;x86_64_"です。\ 前のコマンドで、**AVD9という名前のVMを作成しました****デバイス** "_Nexus 5X_" と **Androidイメージ** "_system-images;android-28;google_apis;x86_64_" を使用)。\
今、次のコマンドで作成した**仮想マシンの一覧を表示できます**: 作成した**仮想マシンを一覧表示**するには:
```bash ```bash
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\avdmanager.bat list avd C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\bin\avdmanager.bat list avd
@ -140,75 +138,131 @@ Name: Pixel_2_API_27
Path: C:\Users\cpolo\.android\avd\Pixel_2_API_27_1.avd Path: C:\Users\cpolo\.android\avd\Pixel_2_API_27_1.avd
Error: Google pixel_2 no longer exists as a device Error: Google pixel_2 no longer exists as a device
``` ```
### 仮想マシンを実行する ### 仮想マシンの起動
> [!WARNING] > [!WARNING]
> macOSの場合、`avdmanager`ツールは`/Users/<username>/Library/Android/sdk/tools/bin/avdmanager`に、`emulator``/Users/<username>/Library/Android/sdk/emulator/emulator`にあります。インストールされている場合です。 > For macOS you can find the `avdmanager` tool in `/Users/<username>/Library/Android/sdk/tools/bin/avdmanager` and the `emulator` in `/Users/<username>/Library/Android/sdk/emulator/emulator` if you have them installed.
作成された仮想マシンをリストする方法はすでに見ましたが、**次の方法でもリストできます**: 既に作成した仮想マシンを一覧表示する方法は見ましたが、**以下の方法でも一覧表示できます**:
```bash ```bash
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -list-avds C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -list-avds
AVD9 AVD9
Pixel_2_API_27 Pixel_2_API_27
``` ```
任意の仮想マシンを作成して**実行することができます**: 次のコマンドを使って、**作成した任意の仮想マシンを実行**できます:
```bash ```bash
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -avd "VirtualMachineName" C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -avd "VirtualMachineName"
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -avd "AVD9" C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -avd "AVD9"
``` ```
より高度なオプションを使用することで、次のような仮想マシンを実行できます: または、より高度なオプションを使用して、次のような仮想マシンを実行できます:
```bash ```bash
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -avd "AVD9" -http-proxy 192.168.1.12:8080 -writable-system C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -avd "AVD9" -http-proxy 192.168.1.12:8080 -writable-system
``` ```
### コマンドラインオプション ### Command line options
ただし、**仮想マシンを起動するために使用できるさまざまな便利なコマンドラインオプションがたくさんあります**。以下にいくつかの興味深いオプションを示しますが、[**完全なリストはここで見つけることができます**](https://developer.android.com/studio/run/emulator-commandline) しかし、仮想マシンを起動するために使える**多数の便利なコマンドラインオプション**が存在します。以下にいくつかの興味深いオプションを示しますが、[**find a complete list here**](https://developer.android.com/studio/run/emulator-commandline)
**ブート** **起動**
- `-snapshot name` : VMスナップショットを開始 - `-snapshot name` : Start VM snapshot
- `-snapshot-list -snapstorage ~/.android/avd/Nexus_5X_API_23.avd/snapshots-test.img` : 記録されたすべてのスナップショットをリスト表示 - `-snapshot-list -snapstorage ~/.android/avd/Nexus_5X_API_23.avd/snapshots-test.img` : 記録されているすべてのスナップショットを一覧表示します
**ネットワーク** **ネットワーク**
- `-dns-server 192.0.2.0, 192.0.2.255` : VMに対してカンマ区切りでDNSサーバを指定できます。 - `-dns-server 192.0.2.0, 192.0.2.255` : VMにカンマ区切りでDNSサーバを指定できます。
- **`-http-proxy 192.168.1.12:8080`** : 使用するHTTPプロキシを指定できますBurpを使用してトラフィックをキャプチャするのに非常に便利です - **`-http-proxy 192.168.1.12:8080`** : 使用するHTTPプロキシを指定できますBurpトラフィックをキャプチャするのに非常に便利)
- プロキシ設定が何らかの理由で機能しない場合は、内部で設定するか、「Super Proxy」や「ProxyDroid」のようなアプリケーションを使用して設定してみてください。 - プロキシ設定が何らかの理由で動作しない場合は、内部で設定するか "Super Proxy" や "ProxyDroid" のようなアプリを使って設定してみてください。
- `-netdelay 200` : ミリ秒単位でネットワーク遅延エミュレーションを設定します。 - `-netdelay 200` : ネットワーク遅延エミュレーションをミリ秒単位で設定します。
- `-port 5556` : コンソールとadbに使用されるTCPポート番号を設定します。 - `-port 5556` : コンソールと adb に使用される TCP ポート番号を設定します。
- `-ports 5556,5559` : コンソールとadbに使用されるTCPポートを設定します。 - `-ports 5556,5559` : コンソールと adb に使用される TCP ポートを設定します。
- **`-tcpdump /path/dumpfile.cap`** : すべてのトラフィックをファイルにキャプチャします - **`-tcpdump /path/dumpfile.cap`** : すべてのトラフィックをファイルにキャプチャします
**システム** **システム**
- `-selinux {disabled|permissive}` : LinuxオペレーティングシステムでSecurity-Enhanced Linuxセキュリティモジュールを無効または許可モードに設定します。 - `-selinux {disabled|permissive}` : Security-Enhanced Linux セキュリティモジュールを disabled または permissive モードに設定します。
- `-timezone Europe/Paris` : 仮想デバイスのタイムゾーンを設定します - `-timezone Europe/Paris` : 仮想デバイスのタイムゾーンを設定します
- `-screen {touch(default)|multi-touch|o-touch}` : エミュレートされたタッチスクリーンモードを設定します。 - `-screen {touch(default)|multi-touch|o-touch}` : エミュレートされたタッチスクリーンモードを設定します。
- **`-writable-system`** : エミュレーションセッション中に書き込み可能なシステムイメージを持つためにこのオプションを使用します。`adb root; adb remount`も実行する必要があります。これは、システムに新しい証明書をインストールするのに非常に便利です。 - **`-writable-system`** : このオプションを使用すると、エミュレーションセッション中にシステムイメージを読み書き可能にできます。`adb root; adb remount` の実行も必要です。システムに新しい証明書をインストールするのに非常に便利です。
## Playストアデバイスのルーティング ## Linux CLI のセットアップ (SDK/AVD quickstart)
Playストアのあるデバイスをダウンロードした場合、直接rootを取得することはできず、このエラーメッセージが表示されます。 公式のCLIツールを使うと、Android Studio を使わずに高速でデバッグ可能なエミュレータを簡単に作成できます。
```bash
# Directory layout
mkdir -p ~/Android/cmdline-tools/latest
# Download commandline tools (Linux)
wget https://dl.google.com/android/repository/commandlinetools-linux-13114758_latest.zip -O /tmp/cmdline-tools.zip
unzip /tmp/cmdline-tools.zip -d ~/Android/cmdline-tools/latest
rm /tmp/cmdline-tools.zip
# Env vars (add to ~/.bashrc or ~/.zshrc)
export ANDROID_HOME=$HOME/Android
export PATH=$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH
# Install core SDK components
sdkmanager --install "platform-tools" "emulator"
# Install a debuggable x86_64 system image (Android 11 / API 30)
sdkmanager --install "system-images;android-30;google_apis;x86_64"
# Create an AVD and run it with a writable /system & snapshot name
avdmanager create avd -n PixelRootX86 -k "system-images;android-30;google_apis;x86_64" -d "pixel"
emulator -avd PixelRootX86 -writable-system -snapshot PixelRootX86_snap
# Verify root (debuggable images allow `adb root`)
adb root
adb shell whoami # expect: root
```
メモ
- システムイメージのフレーバー: google_apis (debuggable、adb rootを許可), google_apis_playstore (not rootable), aosp/default (lightweight).
- ビルドタイプ: userdebug はデバッグ対応イメージで `adb root` を許可することが多い。Play Store images はプロダクションビルドで root をブロックする。
- x86_64 ホストでは、API 28+ 以降で full-system ARM64 エミュレーションはサポートされない。Android 11+ では、per-app ARM-to-x86 translation を含む Google APIs/Play images を使用すると、多くの ARM-only アプリを高速に実行できる。
### CLIからのスナップショット
```bash
# Save a clean snapshot from the running emulator
adb -s emulator-5554 emu avd snapshot save my_clean_setup
# Boot from a named snapshot (if it exists)
emulator -avd PixelRootX86 -writable-system -snapshot my_clean_setup
```
## ARM→x86 バイナリ変換 (Android 11+)
Android 11+ 上の Google APIs および Play Store images は、システムの他の部分をネイティブの x86/x86_64 のままに保ちながら、プロセスごとに ARM アプリのバイナリを変換できます。これはデスクトップで多くの ARM 専用アプリをテストするのに十分高速であることが多いです。
> ヒント: pentests 中は Google APIs x86/x86_64 images を優先してください。Play images は便利ですが `adb root` をブロックします。Play services が特に必要で、root が無いことを受け入れる場合にのみ使用してください。
## Rooting a Play Store device
Play Store を含むデバイスをダウンロードした場合、直接 root を取得することはできず、次のエラーメッセージが表示されます
``` ```
$ adb root $ adb root
adbd cannot run as root in production builds adbd cannot run as root in production builds
``` ```
Using [rootAVD](https://github.com/newbit1/rootAVD) with [Magisk](https://github.com/topjohnwu/Magisk) を使用して、ルート化することができました(例えば、[**この動画**](https://www.youtube.com/watch?v=Wk0ixxmkzAI) **または** [**こちら**](https://www.youtube.com/watch?v=qQicUW0svB8) を参照してください)。 [rootAVD](https://github.com/newbit1/rootAVD) と [Magisk](https://github.com/topjohnwu/Magisk) を使用して root 化できました(例えば [**this video**](https://www.youtube.com/watch?v=Wk0ixxmkzAI) **or** [**this one**](https://www.youtube.com/watch?v=qQicUW0svB8) を参照してください)。
## Burp証明書のインストール ## Burp Certificate のインストール
カスタム CA 証明書のインストール方法は、次のページを確認してください:
カスタムCA証明書のインストール方法については、以下のページを確認してください
{{#ref}} {{#ref}}
install-burp-certificate.md install-burp-certificate.md
{{#endref}} {{#endref}}
## 便利なAVDオプション ## 便利な AVD オプション
### スナップショットを撮る ### スナップショットを取得
**GUIを使用して**、いつでもVMのスナップショットを撮ることができます いつでも **GUI を使用して** VM のスナップショットを取得できます:
![](<../../images/image (234).png>) ![](<../../images/image (234).png>)
## 参考
- [Build a Repeatable Android Bug Bounty Lab: Emulator vs Magisk, Burp, Frida, and Medusa](https://www.yeswehack.com/learn-bug-bounty/android-lab-mobile-hacking-tools)
- [Android Emulator command line](https://developer.android.com/studio/run/emulator-commandline)
- [Run ARM apps on the Android Emulator (x86 translation)](https://android-developers.googleblog.com/2020/03/run-arm-apps-on-android-emulator.html)
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,48 +2,102 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## インストール ## インストール
**frida tools** をインストールします: 以下をインストールしてください: **frida tools**
```bash ```bash
pip install frida-tools pip install frida-tools
pip install frida pip install frida
``` ```
**Androidに** **frida server** を**ダウンロードしてインストール**します ([Download the latest release](https://github.com/frida/frida/releases)).\ **ダウンロードしてインストール** を android 上で **frida server** を導入してください ([Download the latest release](https://github.com/frida/frida/releases)).\
adbをルートモードで再起動し、接続してfrida-serverをアップロードし、実行権限を与えてバックグラウンドで実行するためのワンライナー: adb を root モードで再起動し、接続し、frida-server をアップロードして exec 権限を付与し、バックグラウンドで実行するワンライナー:
```bash ```bash
adb root; adb connect localhost:6000; sleep 1; adb push frida-server /data/local/tmp/; adb shell "chmod 755 /data/local/tmp/frida-server"; adb shell "/data/local/tmp/frida-server &" adb root; adb connect localhost:6000; sleep 1; adb push frida-server /data/local/tmp/; adb shell "chmod 755 /data/local/tmp/frida-server"; adb shell "/data/local/tmp/frida-server &"
``` ```
**動作確認**: **チェック** それが **動作している**:
```bash ```bash
frida-ps -U #List packages and processes frida-ps -U #List packages and processes
frida-ps -U | grep -i <part_of_the_package_name> #Get all the package name frida-ps -U | grep -i <part_of_the_package_name> #Get all the package name
``` ```
## Frida server vs. Gadget (root vs. no-root)
FridaでAndroidアプリを扱う一般的な方法は2つあります:
- Frida server (rooted devices): 任意のプロセスにアタッチできるよう、ネイティブのデーモンをプッシュして実行します。
- Frida Gadget (no root): APK内にFridaをshared libraryとしてバンドルし、ターゲットプロセス内で自動ロードさせます。
Frida server (rooted)
```bash
# Download the matching frida-server binary for your device's arch
# https://github.com/frida/frida/releases
adb root
adb push frida-server-<ver>-android-<arch> /data/local/tmp/frida-server
adb shell chmod 755 /data/local/tmp/frida-server
adb shell /data/local/tmp/frida-server & # run at boot via init/magisk if desired
# From host, list processes and attach
frida-ps -Uai
frida -U -n com.example.app
```
Frida Gadget (no-root)
1) APK をアンパックし、gadget の .so と設定を追加します:
- lib/<abi>/ (例: lib/arm64-v8a/) に libfrida-gadget.so を配置します
- assets/frida-gadget.config を作成し、スクリプト読み込み設定を記述します
frida-gadget.config の例
```json
{
"interaction": { "type": "script", "path": "/sdcard/ssl-bypass.js" },
"runtime": { "logFile": "/sdcard/frida-gadget.log" }
}
```
2) ガジェットを参照/ロードして、早期に初期化されるようにする:
- 最も簡単: 小さな Java スタブを Application.onCreate() に追加して System.loadLibrary("frida-gadget") を呼び出す、または既に存在するネイティブライブラリのロードを利用する。
3) APK をリパックして署名し、インストールする:
```bash
apktool d app.apk -o app_m
# ... add gadget .so and config ...
apktool b app_m -o app_gadget.apk
uber-apk-signer -a app_gadget.apk -o out_signed
adb install -r out_signed/app_gadget-aligned-debugSigned.apk
```
4) ホストからgadgetプロセスにアタッチする:
```bash
frida-ps -Uai
frida -U -n com.example.app
```
注記
- Gadget は一部の保護機構により検出されることがあるため、名前/パスはステルス化し、必要に応じて遅延/条件付きでロードしてください。
- ハード化されたアプリでは、server + late attach を使ったrooted testingを優先するか、Magisk/Zygiskの隠蔽と組み合わせてください。
## チュートリアル ## チュートリアル
### [チュートリアル 1](frida-tutorial-1.md) ### [Tutorial 1](frida-tutorial-1.md)
**出典**: [https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1](https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1)\ **出典**: [https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1](https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1)\
**APK**: [https://github.com/t0thkr1s/frida-demo/releases](https://github.com/t0thkr1s/frida-demo/releases)\ **APK**: [https://github.com/t0thkr1s/frida-demo/releases](https://github.com/t0thkr1s/frida-demo/releases)\
**ソースコード**: [https://github.com/t0thkr1s/frida-demo](https://github.com/t0thkr1s/frida-demo) **ソースコード**: [https://github.com/t0thkr1s/frida-demo](https://github.com/t0thkr1s/frida-demo)
**[リンクをクリックして読む](frida-tutorial-1.md)。** **詳しくは [link to read it](frida-tutorial-1.md) を参照してください。**
### [チュートリアル 2](frida-tutorial-2.md) ### [Tutorial 2](frida-tutorial-2.md)
**出典**: [https://11x256.github.io/Frida-hooking-android-part-2/](https://11x256.github.io/Frida-hooking-android-part-2/) (パート 2, 3 & 4)\ **出典**: [https://11x256.github.io/Frida-hooking-android-part-2/](https://11x256.github.io/Frida-hooking-android-part-2/) (Parts 2, 3 & 4)\
**APKとソースコード**: [https://github.com/11x256/frida-android-examples](https://github.com/11x256/frida-android-examples) **APKs and Source code**: [https://github.com/11x256/frida-android-examples](https://github.com/11x256/frida-android-examples)
**[リンクをクリックして読む。](frida-tutorial-2.md)** **詳しくは [ link to read it.](frida-tutorial-2.md) を参照してください。**
### [チュートリアル 3](owaspuncrackable-1.md) ### [Tutorial 3](owaspuncrackable-1.md)
**出典**: [https://joshspicer.com/android-frida-1](https://joshspicer.com/android-frida-1)\ **出典**: [https://joshspicer.com/android-frida-1](https://joshspicer.com/android-frida-1)\
**APK**: [https://github.com/OWASP/owasp-mstg/blob/master/Crackmes/Android/Level_01/UnCrackable-Level1.apk](https://github.com/OWASP/owasp-mstg/blob/master/Crackmes/Android/Level_01/UnCrackable-Level1.apk) **APK**: [https://github.com/OWASP/owasp-mstg/blob/master/Crackmes/Android/Level_01/UnCrackable-Level1.apk](https://github.com/OWASP/owasp-mstg/blob/master/Crackmes/Android/Level_01/UnCrackable-Level1.apk)
**[リンクをクリックして読む](owaspuncrackable-1.md)。** **詳しくは [link to read it](owaspuncrackable-1.md) を参照してください。**
**ここでさらに素晴らしいFridaスクリプトを見つけることができます:** [**https://codeshare.frida.re/**](https://codeshare.frida.re) **さらに多くのAwesome Fridaスクリプトはここで見つかります:** [**https://codeshare.frida.re/**](https://codeshare.frida.re)
## クイック例 ## クイック例
@ -60,7 +114,7 @@ frida -U --no-pause -l disableRoot.js -f owasp.mstg.uncrackable1
#frozen so that the instrumentation can occur, and the automatically #frozen so that the instrumentation can occur, and the automatically
#continue execution with our modified code. #continue execution with our modified code.
``` ```
### 基本的なPythonスクリプト ### 基本的な Python スクリプト
```python ```python
import frida, sys import frida, sys
@ -71,9 +125,9 @@ print('[ * ] Running Frida Demo application')
script.load() script.load()
sys.stdin.read() sys.stdin.read()
``` ```
### パラメータなし関数をフックする ### パラメータなし関数をフックする
クラス `sg.vantagepoint.a.c` の関数 `a()` をフックします。 クラス `sg.vantagepoint.a.c` の関数 `a()` をフックする
```javascript ```javascript
Java.perform(function () { Java.perform(function () {
; rootcheck1.a.overload().implementation = function() { ; rootcheck1.a.overload().implementation = function() {
@ -83,14 +137,14 @@ return false;
}; };
}); });
``` ```
Javaの`exit()`をフックする java の `exit()` を Hook
```javascript ```javascript
var sysexit = Java.use("java.lang.System") var sysexit = Java.use("java.lang.System")
sysexit.exit.overload("int").implementation = function (var_0) { sysexit.exit.overload("int").implementation = function (var_0) {
send("java.lang.System.exit(I)V // We avoid exiting the application :)") send("java.lang.System.exit(I)V // We avoid exiting the application :)")
} }
``` ```
MainActivityの`.onStart()``.onCreate()`をフックする Hook MainActivity `.onStart()` & `.onCreate()`
```javascript ```javascript
var mainactivity = Java.use("sg.vantagepoint.uncrackable1.MainActivity") var mainactivity = Java.use("sg.vantagepoint.uncrackable1.MainActivity")
mainactivity.onStart.overload().implementation = function () { mainactivity.onStart.overload().implementation = function () {
@ -104,7 +158,7 @@ send("MainActivity.onCreate() HIT!!!")
var ret = this.onCreate.overload("android.os.Bundle").call(this, var_0) var ret = this.onCreate.overload("android.os.Bundle").call(this, var_0)
} }
``` ```
Androidの`.onCreate()`をフックする Hook android `.onCreate()`
```javascript ```javascript
var activity = Java.use("android.app.Activity") var activity = Java.use("android.app.Activity")
activity.onCreate.overload("android.os.Bundle").implementation = function ( activity.onCreate.overload("android.os.Bundle").implementation = function (
@ -114,9 +168,9 @@ send("Activity HIT!!!")
var ret = this.onCreate.overload("android.os.Bundle").call(this, var_0) var ret = this.onCreate.overload("android.os.Bundle").call(this, var_0)
} }
``` ```
### パラメータを持つ関数のフックと値の取得 ### Hooking パラメータ付き関数のフックと値の取得
復号化関数をフックします。入力を印刷し、元の関数を呼び出して入力を復号化し、最後に平文データを印刷します: decryption functionをフックします。入力を表示し、元の関数を呼び出して入力をdecryptし、最後にplain dataを表示します:
```javascript ```javascript
function getString(data) { function getString(data) {
var ret = "" var ret = ""
@ -141,9 +195,9 @@ send("Decrypted flag: " + flag)
return ret //[B return ret //[B
} }
``` ```
### フック関数と入力を使って呼び出す ### 関数をHookして自分の入力で呼び出す
文字列を受け取る関数をフックし、別の文字列で呼び出します([こちら](https://11x256.github.io/Frida-hooking-android-part-2/)から)。 文字列を受け取る関数をHookし、別の文字列で呼び出す (from [here](https://11x256.github.io/Frida-hooking-android-part-2/))
```javascript ```javascript
var string_class = Java.use("java.lang.String") // get a JS wrapper for java's String class var string_class = Java.use("java.lang.String") // get a JS wrapper for java's String class
@ -156,11 +210,11 @@ console.log("Return value: " + ret)
return ret return ret
} }
``` ```
### すでに作成されたクラスのオブジェクトを取得する ### に作成されたクラスのオブジェクトを取得する方法
作成されたオブジェクトの属性を抽出したい場合は、これを使用できます。 作成済みオブジェクトの属性を抽出したい場合は、これを使用できます。
この例では、クラス my_activity のオブジェクトを取得し、オブジェクトのプライベート属性を印刷する .secret() 関数を呼び出す方法を示します。 この例では、クラス my_activity のオブジェクトを取得し、オブジェクトのプライベート属性を出力する .secret() 関数を呼び出す方法を示します:
```javascript ```javascript
Java.choose("com.example.a11x256.frida_test.my_activity", { Java.choose("com.example.a11x256.frida_test.my_activity", {
onMatch: function (instance) { onMatch: function (instance) {
@ -171,10 +225,16 @@ console.log("Result of secret func: " + instance.secret())
onComplete: function () {}, onComplete: function () {},
}) })
``` ```
## その他のFridaチュートリアル ## その他の Frida チュートリアル
- [https://github.com/DERE-ad2001/Frida-Labs](https://github.com/DERE-ad2001/Frida-Labs) - [https://github.com/DERE-ad2001/Frida-Labs](https://github.com/DERE-ad2001/Frida-Labs)
- [Advanced Frida Usageブログシリーズのパート1: IOS暗号化ライブラリ](https://8ksec.io/advanced-frida-usage-part-1-ios-encryption-libraries-8ksec-blogs/) - [Advanced Frida Usage ブログシリーズのパート1: IOS 暗号化ライブラリ](https://8ksec.io/advanced-frida-usage-part-1-ios-encryption-libraries-8ksec-blogs/)
## 参考
- [再現可能な Android Bug Bounty ラボを構築する: Emulator vs Magisk, Burp, Frida, and Medusa](https://www.yeswehack.com/learn-bug-bounty/android-lab-mobile-hacking-tools)
- [Frida Gadget ドキュメント](https://frida.re/docs/gadget/)
- [Frida releasesサーバーバイナリ](https://github.com/frida/frida/releases)
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,20 +1,32 @@
# Burp証明書のインストール # Burp Certificate のインストール
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## 仮想マシンで ## ADB経由のシステム全体プロキシ
まず最初に、BurpからDer証明書をダウンロードする必要があります。これは、_**Proxy**_ --> _**Options**_ --> _**Import / Export CA certificate**_ で行えます。 全てのアプリがインターセプタBurp/mitmproxyを経由してトラフィックをルーティングするように、グローバルな HTTP プロキシを設定します:
```bash
# Set proxy (device/emulator must reach your host IP)
adb shell settings put global http_proxy 192.168.1.2:8080
# Clear proxy
adb shell settings put global http_proxy :0
```
ヒント: In Burp, bind your listener to 0.0.0.0 so devices on the LAN can connect (Proxy -> Options -> Proxy Listeners).
## 仮想マシン上で
まず最初に、Burp から Der 証明書をダウンロードする必要があります。これは _**Proxy**_ --> _**Options**_ --> _**Import / Export CA certificate**_ で行えます。
![](<../../images/image (367).png>) ![](<../../images/image (367).png>)
**Der形式で証明書をエクスポート**し、**Android**が**理解できる形式**に**変換**します。**AVDのAndroidマシンでburp証明書を設定するためには、**このマシンを**`-writable-system`**オプションで**実行する必要があります。\ **証明書を Der フォーマットでエクスポートする** そしてそれを **変換**して、**Android** が**理解**できる形式にします。なお、**AVD の Android マシンに Burp 証明書を設定するためには** このマシンを **`-writable-system`** オプションを付けて**実行**する必要があります。\
例えば、次のように実行できます: 例えば次のように実行できます:
```bash ```bash
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -avd "AVD9" -http-proxy 192.168.1.12:8080 -writable-system C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -avd "AVD9" -http-proxy 192.168.1.12:8080 -writable-system
``` ```
次に、**burpの証明書を設定するには**: 次に、**burps certificate を設定するには**:
```bash ```bash
openssl x509 -inform DER -in burp_cacert.der -out burp_cacert.pem openssl x509 -inform DER -in burp_cacert.der -out burp_cacert.pem
CERTHASHNAME="`openssl x509 -inform PEM -subject_hash_old -in burp_cacert.pem | head -1`.0" CERTHASHNAME="`openssl x509 -inform PEM -subject_hash_old -in burp_cacert.pem | head -1`.0"
@ -25,39 +37,43 @@ adb shell mv /sdcard/$CERTHASHNAME /system/etc/security/cacerts/ #Move to correc
adb shell chmod 644 /system/etc/security/cacerts/$CERTHASHNAME #Assign privileges adb shell chmod 644 /system/etc/security/cacerts/$CERTHASHNAME #Assign privileges
adb reboot #Now, reboot the machine adb reboot #Now, reboot the machine
``` ```
**マシンが再起動を完了すると**、Burp証明書が使用されます マシンが再起動を完了すると、Burp 証明書が使用されます!
## Magiscを使用する ## Magisc の使用
デバイスを**Magiscでルート化した**場合(エミュレーターかもしれません)、**前の手順**に従ってBurp証明書をインストールできない場合、**ファイルシステムが読み取り専用**で書き込み可能に再マウントできない場合、別の方法があります。 もし Magisc でデバイスをルート化している(エミュレータの可能性もあります)、そしてファイルシステムが読み取り専用で remount して書き込み可能にできないために前の手順で Burp 証明書をインストールできない場合、別の方法があります。
[**このビデオ**](https://www.youtube.com/watch?v=qQicUW0svB8)で説明されているように、次のことを行う必要があります: [**this video**](https://www.youtube.com/watch?v=qQicUW0svB8) で説明されているように、次の操作を行います:
1. **CA証明書をインストールする**DER Burp証明書を**ドラッグ&ドロップ**し、モバイルで拡張子を`.crt`に**変更**してダウンロードフォルダーに保存し、`証明書をインストール` -> `CA証明書`に進みます。 1. **CA 証明書をインストールする**: DER 形式の Burp 証明書の拡張子を `.crt` に変更してモバイルにドラッグドロップし、Downloads フォルダに保存します。次に `Install a certificate` -> `CA certificate` へ移動します。
<figure><img src="../../images/image (53).png" alt="" width="164"><figcaption></figcaption></figure> <figure><img src="../../images/image (53).png" alt="" width="164"><figcaption></figcaption></figure>
- `信頼できる資格情報` -> `ユーザー`に進んで、証明書が正しく保存されていることを確認します - `Trusted credentials` -> `USER` に移動して証明書が正しく保存されていることを確認します
<figure><img src="../../images/image (54).png" alt="" width="334"><figcaption></figcaption></figure> <figure><img src="../../images/image (54).png" alt="" width="334"><figcaption></figcaption></figure>
2. **システム信頼にする**Magiscモジュール[MagiskTrustUserCerts](https://github.com/NVISOsecurity/MagiskTrustUserCerts).zipファイル)をダウンロードし、**ドラッグ&ドロップ**して電話に移動し、電話の**Magicsアプリ**の**`モジュール`**セクションに行き、**`ストレージからインストール`**をクリックし、`.zip`モジュールを選択してインストール後に**再起動**します: 2. **システムで信頼されるようにする**: Magisc モジュール [MagiskTrustUserCerts](https://github.com/NVISOsecurity/MagiskTrustUserCerts).zip ファイル)をダウンロードし、電話にドラッグ&ドロップします。電話の **Magics app** を開き、**`Modules`** セクションに移動して **`Install from storage`** をクリックし、.zip モジュールを選択してインストール後に電話を **reboot** します:
<figure><img src="../../images/image (55).png" alt="" width="345"><figcaption></figcaption></figure> <figure><img src="../../images/image (55).png" alt="" width="345"><figcaption></figcaption></figure>
- 再起動後、`信頼できる資格情報` -> `システム`に進み、Postswigger証明書がそこにあることを確認します。 - 再起動後、`Trusted credentials` -> `SYSTEM` に移動して Postswigger 証明書が存在することを確認します
<figure><img src="../../images/image (56).png" alt="" width="314"><figcaption></figcaption></figure> <figure><img src="../../images/image (56).png" alt="" width="314"><figcaption></figcaption></figure>
## Android 14以降 ### Magisc モジュールの作り方を学ぶ
最新のAndroid 14リリースでは、システム信頼の証明書機関CA証明書の取り扱いに大きな変化が見られました。以前は、これらの証明書は**`/system/etc/security/cacerts/`**に格納されており、ルート権限を持つユーザーによってアクセスおよび変更可能で、システム全体に即座に適用されていました。しかし、Android 14では、ストレージの場所が**`/apex/com.android.conscrypt/cacerts`**に移動され、**`/apex`**パス内のディレクトリであり、本質的に不変です。 Check [https://medium.com/@justmobilesec/magisk-for-mobile-pentesting-rooting-android-devices-and-building-custom-modules-part-ii-22badc498437](https://medium.com/@justmobilesec/magisk-for-mobile-pentesting-rooting-android-devices-and-building-custom-modules-part-ii-22badc498437)
**APEX cacertsパス**を読み書き可能に再マウントしようとすると、システムがそのような操作を許可しないため、失敗します。一時ファイルシステムtmpfsでディレクトリをアンマウントまたはオーバーレイしようとする試みも不変性を回避できず、アプリケーションはファイルシステムレベルでの変更に関係なく、元の証明書データにアクセスし続けます。この耐性は、**`/apex`**マウントがPRIVATE伝播で構成されているためであり、**`/apex`**ディレクトリ内の変更が他のプロセスに影響を与えないことを保証します。 ## Android 14 以降
Androidの初期化には`init`プロセスが関与しており、オペレーティングシステムを起動すると同時にZygoteプロセスも開始されます。このプロセスは、新しいマウントネームスペースを持つアプリケーションプロセスを起動する責任があり、プライベートな**`/apex`**マウントを含むため、このディレクトリへの変更を他のプロセスから隔離します。 最新の Android 14 リリースでは、system-trusted の Certificate Authority (CA) 証明書の扱いに大きな変更がありました。以前はこれらの証明書は **`/system/etc/security/cacerts/`** に保存され、root 権限のあるユーザーがアクセス・変更できたため、システム全体に即時反映されていました。しかし Android 14 では、保存場所が **`/apex/com.android.conscrypt/cacerts`****`/apex`** パス内のディレクトリに移動されており、これは本質的に不変immutableす。
それでも、**`/apex`**ディレクトリ内のシステム信頼のCA証明書を変更する必要がある場合の回避策があります。これは、PRIVATE伝播を削除するために**`/apex`**を手動で再マウントし、書き込み可能にすることを含みます。このプロセスには、**`/apex/com.android.conscrypt`**の内容を別の場所にコピーし、読み取り専用制約を排除するために**`/apex/com.android.conscrypt`**ディレクトリをアンマウントし、その後、内容を**`/apex`**内の元の場所に復元することが含まれます。このアプローチは、システムクラッシュを避けるために迅速な行動を必要とします。これらの変更をシステム全体に適用するためには、`system_server`を再起動することが推奨されており、これによりすべてのアプリケーションが再起動され、システムが一貫した状態に戻ります。 APEX の cacerts パスを書き込み可能に remount しようとすると失敗します。システムがそのような操作を許可しないためです。ディレクトリをアンマウントしたり tmpfs でオーバーレイしたりしても不変性を回避できず、ファイルシステムレベルで変更を加えてもアプリケーションは元の証明書データにアクセスし続けます。この耐性は、**`/apex`** マウントが PRIVATE propagation に設定されているためで、**`/apex`** 内での変更が他のプロセスに影響を与えないようになっています。
Android の初期化では `init` プロセスが起動し、OS の起動時に Zygote プロセスも立ち上げます。Zygote は、新しいマウントネームスペースを持つアプリケーションプロセスを起動する役割を担っており、そのネームスペースには private な **`/apex`** マウントが含まれます。これにより、このディレクトリへの変更は他のプロセスから分離されます。
それでも、**`/apex`** ディレクトリ内の system-trusted CA 証明書を修正する必要がある場合の回避策が存在します。これは、**`/apex`** の PRIVATE propagation を解除して書き込み可能にするために手動で remount する方法です。手順は、**`/apex/com.android.conscrypt`** の内容を別の場所にコピーし、**`/apex/com.android.conscrypt`** をアンマウントして読み取り専用の制約を取り除き、内容を **`/apex`** の元の場所に戻す、というものです。この操作はシステムクラッシュを避けるために素早く行う必要があります。変更をシステム全体に反映させるためには、`system_server` を再起動する(これにより全アプリケーションが実質的に再起動され、システムが整合した状態になる)ことを推奨します。
```bash ```bash
# Create a separate temp directory, to hold the current certificates # Create a separate temp directory, to hold the current certificates
# Otherwise, when we add the mount we can't read the current certs anymore. # Otherwise, when we add the mount we can't read the current certs anymore.
@ -115,28 +131,28 @@ wait # Launched in parallel - wait for completion here
echo "System certificate injected" echo "System certificate injected"
``` ```
### NSEnterを通じたバインドマウント ### Bind-mounting through NSEnter
1. **書き込み可能なディレクトリの設定**: 最初に、既存の非APEXシステム証明書ディレクトリの上に`tmpfs`をマウントすることで、書き込み可能なディレクトリが確立されます。これは次のコマンドで実現されます: 1. **Setting Up a Writable Directory**: 最初に、既存の non-APEX システム証明書ディレクトリの上に `tmpfs` をマウントして、書き込み可能なディレクトリを作成します。これは以下のコマンドで実行します:
```bash ```bash
mount -t tmpfs tmpfs /system/etc/security/cacerts mount -t tmpfs tmpfs /system/etc/security/cacerts
``` ```
2. **CA証明書の準備**: 書き込み可能なディレクトリのセットアップに続いて、使用する予定のCA証明書をこのディレクトリにコピーする必要があります。これには、`/apex/com.android.conscrypt/cacerts/`からデフォルトの証明書をコピーすることが含まれる場合があります。これらの証明書の権限とSELinuxラベルを適切に調整することが重要です。 2. **CA証明書の準備**: 書き込み可能なディレクトリを設定した後、使用する CA certificates をそのディレクトリにコピーします。これはデフォルトの証明書を `/apex/com.android.conscrypt/cacerts/` からコピーすることを含む場合があります。これらの証明書のパーミッションと SELinux ラベルを適切に調整することが重要です。
3. **Zygoteのバインドマウント**: `nsenter`を使用して、Zygoteのマウントネームスペースに入ります。ZygoteはAndroidアプリケーションを起動するプロセスであり、以降に起動されるすべてのアプリケーションが新しく構成されたCA証明書を利用することを保証するためにこのステップが必要です。使用されるコマンドは: 3. **Zygote 用の Bind Mount**: `nsenter` を用いて Zygote の mount namespace に入ります。Zygote は Android アプリケーションを起動するプロセスであり、この手順により以降に起動されるすべてのアプリが新しく設定した CA certificates を利用するようになります。使用するコマンドは:
```bash ```bash
nsenter --mount=/proc/$ZYGOTE_PID/ns/mnt -- /bin/mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts nsenter --mount=/proc/$ZYGOTE_PID/ns/mnt -- /bin/mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts
``` ```
これにより、新しく開始されるすべてのアプリが更新されたCA証明書の設定に従うことが保証されます。 これにより、新しく起動するすべてのアプリが更新された CA certificates の設定に従うようになります。
4. **実行中のアプリへの変更適用**: 既に実行中のアプリケーションに変更を適用するには、`nsenter`を再度使用して各アプリの名前空間に個別に入り、同様のバインドマウントを実行します。必要なコマンドは: 4. **実行中のアプリへの変更適用**: 既に実行中のアプリに変更を適用するには、`nsenter` を再度使用して各アプリの namespace に個別に入り、同様の bind mount を行います。必要なコマンドは:
```bash ```bash
nsenter --mount=/proc/$APP_PID/ns/mnt -- /bin/mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts nsenter --mount=/proc/$APP_PID/ns/mnt -- /bin/mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts
``` ```
5. **代替アプローチ - ソフトリブート**: 代替手法は、`init`プロセスPID 1でバインドマウントを行い、その後`stop && start`コマンドでオペレーティングシステムをソフトリブートすることです。このアプローチは、すべてのネームスペースに変更を伝播させ、各実行中のアプリを個別に対処する必要を回避します。しかし、この方法はリブートの不便さから一般的にはあまり好まれません。 5. **代替アプローチ - ソフト再起動**:別の方法としては、`init` プロセスPID 1で bind mount を実行し、その後 `stop && start` コマンドでオペレーティングシステムをソフト再起動する方法があります。このアプローチは変更をすべての namespaces に伝播させ、各実行中の app を個別に対処する必要を回避します。ただし、再起動の手間がかかるため、この方法は一般的にはあまり好まれません。
## 参考文献 ## 参考資料
- [https://httptoolkit.com/blog/android-14-install-system-ca-certificate/](https://httptoolkit.com/blog/android-14-install-system-ca-certificate/)
- [Android 14: Install a system CA certificate on a rooted device](https://httptoolkit.com/blog/android-14-install-system-ca-certificate/)
- [Build a Repeatable Android Bug Bounty Lab: Emulator vs Magisk, Burp, Frida, and Medusa](https://www.yeswehack.com/learn-bug-bounty/android-lab-mobile-hacking-tools)
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}