Android アプリケーション Pentesting

Reading time: 60 minutes

tip

AWSハッキングを学び、実践する:HackTricks Training AWS Red Team Expert (ARTE)
GCPハッキングを学び、実践する:HackTricks Training GCP Red Team Expert (GRTE) Azureハッキングを学び、実践する:HackTricks Training Azure Red Team Expert (AzRTE)

HackTricksをサポートする

Android Applications Basics

このページを最初に読むことを強く推奨します。Android セキュリティに関連する最も重要な部分と、Android アプリケーションで最も危険なコンポーネントについて理解するためです:

Android Applications Basics

ADB (Android Debug Bridge)

これは、エミュレータでも実機でも Android デバイスに接続するために必要な主要なツールです。
ADB はコンピュータから USB または Network 経由でデバイスを制御できます。このユーティリティはファイルの双方向の コピー、アプリの インストールアンインストール、シェルコマンドの 実行、データの バックアップ、ログの 読み取り などの機能を提供します。

adbの使用方法を学ぶには、次のADB Commandsのリストを参照してください。

Smali

時には、modify the application code によって hidden information(難読化されたパスワードやフラグなど)にアクセスすることが有用です。その場合、APKを逆コンパイルしてコードを修正し、再コンパイルすることが役立つことがあります。
In this tutorial you can learn how to decompile and APK, modify Smali code and recompile the APK with the new functionality. これは、これから紹介する動的解析中のいくつかのテストに対する代替手段として非常に有用です。したがって、この可能性を常に念頭に置いてください。

Other interesting tricks

bash
adb shell pm list packages
com.android.insecurebankv2

adb shell pm path com.android.insecurebankv2
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
  • すべての splits と base apks を APKEditor でマージする:
bash
mkdir splits
adb shell pm path com.android.insecurebankv2 | cut -d ':' -f 2 | xargs -n1 -i adb pull {} splits
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
java -jar uber-apk-signer.jar -a merged.apk --allowResign -o merged_signed

ケーススタディと脆弱性

Air Keyboard Remote Input Injection

Android Rooting Frameworks Manager Auth Bypass Syscall Hook

静的解析

まず第一に、APK を解析するにはデコンパイラを使って Java コードを確認する 必要があります。
ここを読んで利用可能な各種 decompiler に関する情報を見つけてください

興味深い情報の探索

APK の strings を見るだけでも、passwords, URLs (https://github.com/ndelphit/apkurlgrep), api keys, encryption, bluetooth uuids, tokens などの興味深い情報を検索できます… コード実行の backdoors や認証 backdoors(アプリにハードコードされた管理者資格情報)も探してください。

Firebase

firebase URLs に特に注意を払い、設定が不適切でないか確認してください。 More information about whats is FIrebase and how to exploit it here.

アプリケーションの基本理解 - Manifest.xml, strings.xml

アプリケーションの Manifest.xmlstrings.xml ファイルを調査することで、潜在的なセキュリティ脆弱性が明らかになることがあります。これらのファイルはデコンパイラを使うか、APK の拡張子を .zip に変更して展開することでアクセスできます。

Manifest.xml から特定される脆弱性には次のものが含まれます:

  • Debuggable Applications: Manifest.xml 内で debuggable="true" に設定されたアプリは危険です。デバッグ接続が許可され、これにより悪用される可能性があります。デバッグ可能なアプリの発見と悪用方法については、デバイス上の debuggable アプリを見つけて悪用するチュートリアルを参照してください。
  • Backup Settings: 機密情報を扱うアプリでは、android:allowBackup="false" を明示的に設定しておくべきです。特に usb debugging が有効な場合、adb 経由での無許可なデータバックアップを防ぐためです。
  • Network Security: カスタムなネットワークセキュリティ設定(android:networkSecurityConfig="@xml/network_security_config")は、res/xml/ にあり、証明書ピンや HTTP トラフィックの設定などのセキュリティ詳細を指定できます。例として、特定ドメインに対して HTTP トラフィックを許可する設定があります。
  • Exported Activities and Services: マニフェスト内でエクスポートされた activities や services を特定すると、悪用される可能性のあるコンポーネントが明らかになります。ダイナミックテスト中にこれらのコンポーネントをどのように悪用できるかを詳しく分析してください。
  • Content Providers and FileProviders: 公開された content providers はデータの無許可アクセスや改ざんを許す可能性があります。FileProviders の設定も精査すべきです。
  • Broadcast Receivers and URL Schemes: これらのコンポーネントは悪用される可能性があり、特に URL スキームが入力に対してどのように扱われているかに注意してください。
  • SDK Versions: minSdkVersion, targetSDKVersion, maxSdkVersion の属性はサポートされる Android バージョンを示します。古く脆弱な Android バージョンをサポートしないことがセキュリティ上重要です。

strings.xml ファイルからは、API キー、カスタムスキーマ、その他開発者メモなどの機密情報が見つかることがあり、これらのリソースを注意深く確認する必要があります。

Tapjacking

Tapjacking は、悪意のあるアプリケーションが被害者アプリの上に位置して起動する攻撃です。被害者アプリを視覚的に覆った状態で、悪意のある UI がユーザを騙して操作させ、その操作を被害者アプリに透過的に渡すよう設計されています。
結果的に、ユーザは実際には被害者アプリ上で操作を行っていることに気づかされないまま操作してしまいます。

Find more information in:

Tapjacking

Task Hijacking

launchModesingleTask に設定され、かつ taskAffinity が定義されていない activity は Task Hijacking に対して脆弱です。これは、悪意のあるアプリをインストールして本物のアプリより先に起動すると、本物のアプリのタスクを乗っ取る 可能性があることを意味します(そのためユーザは本物のアプリを使っていると思い込み、実際には悪意のあるアプリとやり取りしていることになります)。

More info in:

Android Task Hijacking

安全でないデータ保存

Internal Storage

Android では、内部ストレージに格納されたファイルはそれを作成したアプリのみがアクセスできるように設計されています。このセキュリティ対策は OS により強制され、多くのアプリのセキュリティ要件には概ね十分です。しかし、開発者が MODE_WORLD_READABLEMODE_WORLD_WRITABLE といったモードを利用してファイルを他のアプリ間で共有することがあります。これらのモードは、潜在的に悪意のあるアプリを含む他のアプリからのアクセスを制限しません。

  1. Static Analysis:
  • MODE_WORLD_READABLEMODE_WORLD_WRITABLE の使用は注意深く精査してください。これらのモードはファイルを意図しない、または無許可のアクセスにさらす可能性があります。
  1. Dynamic Analysis:
  • アプリが作成するファイルに設定された権限を確認してください。特に、ファイルが世界中で読み取り可能または書き込み可能に設定されていないかをチェックします。これがあると、デバイスにインストールされた任意のアプリが、その出所や意図に関係なくこれらのファイルを読み取り・変更できる重大なリスクになります。

External Storage

SD カードなどの external storage 上のファイルを扱う際には、次の点に注意してください:

  1. Accessibility:
  • external storage 上のファイルはグローバルに読み書き可能です。つまり、任意のアプリやユーザがこれらのファイルにアクセスできます。
  1. Security Concerns:
  • アクセスが容易なため、機密情報を external storage に保存しないことが推奨されます。
  • external storage は取り外されたり、任意のアプリによってアクセスされる可能性があり、より安全性が低くなります。
  1. Handling Data from External Storage:
  • external storage から取得したデータには常に入力検証を行ってください。これは、データが信頼できないソースから来るため重要です。
  • external storage に実行ファイルや class ファイルを置き、動的にロードすることは強く非推奨です。
  • アプリが external storage から実行可能ファイルを取得する必要がある場合、それらのファイルが動的にロードされる前に署名され暗号的に検証されていることを確認してください。これはアプリのセキュリティ整合性を維持するために重要です。

External storage は /storage/emulated/0 , /sdcard , /mnt/sdcard でアクセスできます

tip

Android 4.4(API 17)以降、SD カードにはアプリごとに専用のディレクトリ構造があり、アプリがアクセスできるのはそのアプリ専用のディレクトリに限定されます。これにより、悪意のあるアプリが別のアプリのファイルへ読み書きアクセスすることを防ぎます。

平文で保存された機密データ

  • Shared preferences: Android は各アプリが簡単に xml ファイルを /data/data/<packagename>/shared_prefs/ に保存できるようにしており、そのフォルダ内に平文で機密情報が保存されていることが時々あります。
  • Databases: Android は各アプリが簡単に sqlite データベースを /data/data/<packagename>/databases/ に保存できるようにしており、そのフォルダ内に平文で機密情報が保存されていることもあります。

Broken TLS

Accept All Certificates

なぜか開発者がすべての証明書を受け入れてしまうことがあります。例えばホスト名が一致しなくても以下のようなコード行で受け入れてしまうことがあります:

java
SSLSocketFactory sf = new cc(trustStore);
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.

Broken Cryptography

Poor Key Management Processes

一部の開発者は機密データをローカルストレージに保存し、コード内にハードコード/予測可能なキーで暗号化します。これは推奨されません。リバースエンジニアリングによって攻撃者が機密情報を抽出できる可能性があるためです。

Use of Insecure and/or Deprecated Algorithms

開発者は認可のchecks、データのstoresenddeprecated algorithmsを使用してはいけません。これらのアルゴリズムの例には RC4、MD4、MD5、SHA1 などがあります。例えばパスワードの保存にhashesを用いる場合、ソルト付きで総当たり攻撃にresistantなハッシュを使用するべきです。

Other checks

  • APKをobfuscateして、攻撃者によるリバースエンジニアリングの労力を増やすことを推奨します。
  • アプリが機密性の高いものである場合(銀行アプリ等)、own checks to see if the mobile is rooted を実行し、それに応じて処理するべきです。
  • アプリが機密性の高いものである場合(銀行アプリ等)、emulator が使用されているかどうかをチェックするべきです。
  • アプリが機密性の高いものである場合(銀行アプリ等)、実行前にcheck it's own integrity before executingして改変されていないか確認するべきです。
  • APKのビルドにどの compiler/packer/obfuscator が使われたかを確認するには APKiD を使用してください

React Native Application

Read the following page to learn how to easily access javascript code of React applications:

React Native Application

Xamarin Applications

Read the following page to learn how to easily access C# code of a xamarin applications:

Xamarin Apps

Superpacked Applications

According to this blog post 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

ツール mariana-trench はアプリケーションのcodescanningしてvulnerabilitiesを発見することができます。このツールは一連のknown sources(ツールに対してplacesを示し、そこでのinputcontrolled by the userである場所)、sinks(悪意あるユーザ入力が被害を引き起こす可能性のあるdangerousplaces)およびrulesを含みます。これらのrulesは、脆弱性を示すsources-sinkscombinationを指します。

この知識を基に、mariana-trench will review the code and find possible vulnerabilities on it

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

Bypass Biometric Authentication

Bypass Biometric Authentication (Android)

Other interesting functions

  • Code execution: Runtime.exec(), ProcessBuilder(), native code:system()
  • Send SMSs: sendTextMessage, sendMultipartTestMessage
  • Native functions declared as native: public native, System.loadLibrary, System.load
  • Read this to learn how to reverse native functions
  • In-memory native code execution via JNI (downloaded shellcode → mmap/mprotect → call):

In Memory Jni Shellcode Execution

Other tricks

content:// protocol



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.

Online Dynamic analysis

次のサイトでfree accountを作成できます: https://appetize.io/. このプラットフォームでは APK をuploadしてexecuteできるため、APK の挙動を確認するのに便利です。

ウェブ上でsee the logs of your applicationしたり、adbを通じて接続することもできます。

ADB 接続のおかげで、エミュレータ内で DrozerFrida を使用できます。

Local Dynamic Analysis

Using an emulator

  • Android Studiox86arm デバイスを作成できます。また、this によれば最新の x86 バージョンは遅い arm エミュレータを使わずとも ARM libraries をサポートします)。
  • セットアップ方法は次のページを参照してください:

AVD - Android Virtual Device

  • Genymotion (Free version: Personal Edition、アカウント作成が必要です。潜在的なエラーを避けるために VirtualBox 付きのバージョンをdownloadすることを推奨します。)_
  • Nox(無料ですが、Frida や Drozer をサポートしていません)。

tip

どのプラットフォームで新しいエミュレータを作成する際も、画面が大きいほどエミュレータは遅くなります。可能であれば小さい画面を選んでください。

Genymotion に Google サービス(Play Store など)をインストールするには、以下画像の赤で示されたボタンをクリックしてください:

また、Genymotion の Android VM の configuration では Bridge Network mode を選択できます(ツールを実行している別の VM から Android VM に接続する場合に有用です)。

Use a physical device

デバッグオプションを有効にし、可能であれば root を取得しておくと便利です:

  1. 設定(Settings)。
  2. (Android 8.0 以降)System を選択。
  3. About phone を選択。
  4. Build number を7回押す。
  5. 戻ると Developer options が表示されます。

一度アプリをインストールしたら、まずはそのアプリを実行して何をするのか、どのように動作するのかを調査して慣れてください。
初期の動的解析は MobSF dynamic analysis + pidcat を用いて行うことを推奨します。これにより、MobSF が多くの興味深いデータをキャプチャする一方で、アプリの動作を学ぶことができます。

Magisk/Zygisk quick notes (recommended on Pixel devices)

  • Magisk アプリで boot.img をパッチし、fastboot 経由でフラッシュして systemless root を取得
  • Zygisk を有効にし、DenyList を使って root を隠す;より強力な隠蔽が必要な場合は LSPosed/Shamiko の使用を検討
  • OTA アップデートから回復するために元の boot.img を保管し、OTA 後に再パッチを行う
  • 画面ミラーリングにはホストで scrcpy を使用

Unintended Data Leakage

Logging

開発者はdebugging informationを公開しないよう注意するべきです。公開されると機密データの leaks に繋がる可能性があります。アプリケーションログを監視して機密情報を特定・保護するために、pidcatadb logcat の使用を推奨します。Pidcat は使いやすさと可読性のために好まれます。

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.
Anyway, it's still recommended to not log sensitive information.

Copy/Paste Buffer Caching

Android の clipboard-based フレームワークはアプリ間のコピー&ペーストを可能にしますが、他のアプリがクリップボードにアクセスできるため機密データが露出するリスクがあります。クレジットカード情報など機密性の高い部分についてはコピー/ペースト機能を無効にすることが重要です。

Crash Logs

アプリがクラッシュしてログを保存する場合、これらのログはリバースエンジニアリングが難しい場合でも攻撃者に有用な情報を与える可能性があります。このリスクを軽減するため、クラッシュ時にログを出力しないか、ネットワーク経由で送信する場合は SSL チャネルを使用するなどの対策を講じてください。

As pentester, try to take a look to these logs.

Analytics Data Sent To 3rd Parties

多くのアプリは Google Adsense のようなサービスを統合しており、開発者の不適切な実装により機密データを leak してしまう可能性があります。サードパーティに送信されるデータに機密情報が含まれていないかを確認するため、アプリのトラフィックをインターセプトしてチェックすることを推奨します。

SQLite DBs

ほとんどのアプリは情報を保存するために内部の SQLite データベースを使用します。ペンテスト中は作成されたdatabasestablescolumnsの名前、保存されているすべてのdataを確認してください。そこに機密情報が見つかる可能性があり、それは脆弱性になり得ます。
データベースは通常 /data/data/the.package.name/databases にあり、例: /data/data/com.mwr.example.sieve/databases

もしデータベースが機密情報を保存しencrypted but you can find the password inside the application it's still a vulnerability.

.tables を使ってテーブルを列挙し、.schema <table_name> を使ってテーブルのカラムを列挙します。

Drozer (Exploit Activities, Content Providers and Services)

From Drozer Docs: 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 Android’s Inter-Process Communication (IPC) mechanism and interact with the underlying operating system. .
Drozer はエクスポートされた Activities、exported services、Content Providers をexploitするのに有用なツールです。以下のセクションで学びます。

Exploiting exported Activities

Read this if you want to refresh what is an Android Activity.
また、アクティビティのコードは onCreate メソッドから始まることを忘れないでください。

Authorisation bypass

Activity が exported されている場合、外部アプリからその画面を呼び出すことができます。したがって、sensitive information を扱う Activity が exported されている場合、authentication メカニズムを bypass してアクセスできてしまう可能性があります。

Learn how to exploit exported activities with Drozer.

ADB からも exported activity を起動できます:

  • PackageName is com.example.demo
  • Exported ActivityName is com.example.test.MainActivity
bash
adb shell am start -n com.example.demo/com.example.test.MainActivity

NOTE: MobSF は activity の android:launchModesingleTask/singleInstance を使用していることを悪意のあるものとして検出しますが、this によれば、どうやらこれは古いバージョン(API versions < 21)でのみ危険なようです。

tip

authorisation bypass が常に脆弱性であるとは限らないことに注意してください。bypass の動作方法やどの情報が露出するかによって異なります。

機密情報の漏洩

Activities can also return results. エクスポートされ保護されていない activity が setResult メソッドを呼び出して機密情報を返す場合、機密情報の漏洩が発生します。

Tapjacking

Tapjacking が防止されていない場合、exported activity を悪用してユーザに予期しない操作をさせることができます。詳細は Tapjacking とは(詳細) を参照してください。

Exploiting Content Providers - 機密情報へのアクセスと操作

Content Provider の復習をしたい場合はこちらを読む。
Content providers は基本的にデータを共有するために使用されます。アプリが利用可能な content providers を持っている場合、そこから機密データを抽出できる可能性があります。脆弱である可能性があるため、SQL injectionsPath Traversals のテストを行うことも重要です。

Drozer を使って Content Providers を exploit する方法を学ぶ。

Exploiting Services

Service の復習をしたい場合はこちらを読む。
Service の処理は onStartCommand メソッドで開始されることを覚えておいてください。

Service は基本的にデータを受け取り、処理し、(場合によっては)応答を返すものです。したがってアプリがいくつかの services を export している場合は、何をしているかを理解するためにコードを確認し、機密情報の抽出や認証対策の bypass などを目的に動的にテストするべきです。
Drozer で Services を exploit する方法を学ぶ。

Exploiting Broadcast Receivers

Broadcast Receiver の復習をしたい場合はこちらを読む。
Broadcast Receiver の処理は onReceive メソッドで開始されることを覚えておいてください。

Broadcast receiver は特定の種類のメッセージを待ち受けます。受信側がメッセージをどのように処理するかによって脆弱になる可能性があります。
Drozer で Broadcast Receivers を exploit する方法を学ぶ。

手作業で deep links を探すこともできます。MobSF のようなツールや、this one のようなスクリプトを使って探すことができます。
宣言された schemeadbbrowser を使って開くことができます:

bash
adb shell am start -a android.intent.action.VIEW -d "scheme://hostname/path?param=value" [your.package.name]

モバイルではパッケージ名を省略すると、そのリンクを開くアプリが自動的に呼び出されます。

html
<!-- Browser regular link -->
<a href="scheme://hostname/path?param=value">Click me</a>
<!-- fallback in your url you could try the intent url -->
<a href="intent://hostname#Intent;scheme=scheme;package=your.package.name;S.browser_fallback_url=http%3A%2F%2Fwww.example.com;end">with alternative</a>

実行されるコード

アプリで実行されるコードを見つけるには、deeplink によって呼び出される activity に移動し、関数 onNewIntent を探してください。

Sensitive info

deep link を見つけたら毎回、URL パラメータ経由で機密データ(パスワードなど)を受け取っていないかを確認してください。そうでないと、他のアプリがdeep link をなりすましてそのデータを盗む可能性があります。

Parameters in path

URL のパス内にパラメータを使っている deep link がないかも必ず確認してください。例えば https://api.example.com/v1/users/{username} のような場合、example://app/users?username=../../unwanted-endpoint%3fparam=value のようにパストラバーサルを強制できることがあります。
アプリ内部で正しいエンドポイントを発見できれば、パスの一部がドメイン名として使われている場合の Open Redirect、CSRF トークンなしでユーザ詳細を変更できる場合の account takeover(脆弱なエンドポイントが正しいメソッドを使っている場合)など、他の様々な脆弱性を誘発できる可能性があります。詳細は http://dphoeniixx.com/2020/12/13-2/ を参照してください。

More examples

An interesting bug bounty report about links (/.well-known/assetlinks.json).

Transport Layer Inspection and Verification Failures

  • Certificates are not always inspected properly by Android applications. 多くの場合、アプリは警告を無視して自己署名証明書を受け入れたり、場合によっては HTTP 接続にフォールバックしたりします。
  • Negotiations during the SSL/TLS handshake are sometimes weak, insecure な cipher suite を使用していることがあります。この脆弱性により接続が man-in-the-middle (MITM) 攻撃に対して脆弱になり、攻撃者がデータを復号できる可能性があります。
  • Leakage of private information は、アプリが認証に安全なチャネルを使っている一方で、他のやり取りで非暗号化チャネルを使う場合に発生するリスクです。この設計は、セッション Cookie やユーザ情報などの機密データを悪意ある者による傍受から守れません。

Certificate Verification

ここでは certificate verification に焦点を当てます。サーバの証明書の整合性を検証することはセキュリティ強化のために必須です。TLS の不適切な設定や機密データを暗号化されていないチャネルで送信することは重大なリスクを招きます。サーバ証明書の検証方法や脆弱性対応の詳細手順については、this resource を参照してください。

SSL Pinning

SSL Pinning は、アプリがサーバ証明書をアプリ内に保存された既知のコピーと照合するセキュリティ手法です。この方法は MITM 攻撃を防ぐうえで重要です。機密情報を扱うアプリでは SSL Pinning の実装を強く推奨します。

Traffic Inspection

HTTP トラフィックを検査するには、プロキシツール(例: Burp)の証明書をインストールする必要があります。この証明書をインストールしないと、暗号化されたトラフィックはプロキシ上で見えない場合があります。カスタム CA 証明書のインストールガイドは click here を参照してください。

API Level 24 and above をターゲットにしたアプリケーションは、プロキシの CA 証明書を受け入れるよう Network Security Config の変更が必要です。暗号化トラフィックを検査するにはこの手順が重要です。Network Security Config の変更方法は refer to this tutorial を参照してください。

もし Flutter を使用している場合は、this page の指示に従う必要があります。単に証明書をストアに追加するだけでは動作しないことがあり、Flutter は独自の有効な CA のリストを持っているためです。

Static detection of SSL/TLS pinning

runtime のバイパスを試す前に、APK 内でどこに pinning が強制されているかを静的に把握してください。静的検出はフックやパッチの計画を立て、正しいコードパスに集中するのに役立ちます。

Tool: SSLPinDetect

  • オープンソースの静的解析ユーティリティで、APK を Smali(apktool 経由)にデコンパイルし、SSL/TLS pinning 実装のためにキュレーションされた正規表現パターンをスキャンします。
  • 各マッチについて正確なファイルパス、行番号、コードスニペットを報告します。
  • OkHttp CertificatePinner、カスタム javax.net.ssl.X509TrustManager.checkServerTrusted、SSLContext.init とカスタム TrustManagers/KeyManagers、Network Security Config XML のピンなど、一般的なフレームワークとカスタムコードパスをカバーします。

Install

  • Prereqs: Python >= 3.8, Java on PATH, apktool
bash
git clone https://github.com/aancw/SSLPinDetect
cd SSLPinDetect
pip install -r requirements.txt

使い方

bash
# Basic
python sslpindetect.py -f app.apk -a apktool.jar

# Verbose (timings + per-match path:line + snippet)
python sslpindetect.py -a apktool_2.11.0.jar -f sample/app-release.apk -v

パターンルールの例 (JSON) 独自/カスタムの pinning スタイルを検出するために signatures を使用または拡張します。独自の JSON を読み込んで大規模に scan できます。

json
{
"OkHttp Certificate Pinning": [
"Lcom/squareup/okhttp/CertificatePinner;",
"Lokhttp3/CertificatePinner;",
"setCertificatePinner"
],
"TrustManager Override": [
"Ljavax/net/ssl/X509TrustManager;",
"checkServerTrusted"
]
}

Notes and tips

  • 大規模なアプリを高速にスキャンするには、マルチスレッド処理とメモリマップド I/O を利用する。事前コンパイル済みの正規表現はオーバーヘッドと誤検出を減らす。
  • Pattern collection: https://github.com/aancw/smali-sslpin-patterns
  • 次にトリアージすべき典型的な検出対象:
  • OkHttp: CertificatePinner の使用、setCertificatePinner、okhttp3/okhttp パッケージ参照
  • Custom TrustManagers: javax.net.ssl.X509TrustManager、checkServerTrusted のオーバーライド
  • Custom SSL contexts: SSLContext.getInstance + SSLContext.init をカスタムマネージャーで使用
  • Declarative pins in res/xml network security config と manifest の参照
  • 一致した箇所を利用して、動的テストの前に Frida フック、静的パッチ、または設定レビューを計画する。

SSL Pinning の回避

SSL Pinning が実装されている場合、HTTPS トラフィックを調査するためにこれを回避する必要がある。目的のためのさまざまな方法がある:

一般的な Web 脆弱性の検索

アプリ内で一般的な Web 脆弱性を探すことも重要である。これらの脆弱性の特定と緩和に関する詳細はこの要約の範囲を超えるが、他の場所で広く扱われている。

Frida

Frida は開発者、リバースエンジニア、セキュリティ研究者向けの動的インストルメンテーションツールキットです。
実行中のアプリにアクセスして、ランタイムでメソッドを hook し、挙動を変更したり、値を変更・抽出したり、別コードを実行したりできます...
Android アプリを pentest するなら Frida の使い方を知っておく必要がある。

Anti-instrumentation & SSL pinning bypass workflow

Android Anti Instrumentation And Ssl Pinning Bypass

メモリダンプ - Fridump

アプリがパスワードやニーモニックなど、本来メモリに保存すべきでない機密情報をメモリ内に保持していないか確認する。

Using Fridump3 you can dump the memory of the app with:

bash
# With PID
python3 fridump3.py -u <PID>

# With name
frida-ps -Uai
python3 fridump3.py -u "<Name>"

これは ./dump フォルダにメモリをダンプします。そこで次のようなコマンドで grep できます:

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]+$"

Keystore内の機密データ

AndroidではKeystoreが機密データを保存する最適な場所ですが、十分な権限があれば依然としてアクセス可能です。アプリケーションはここに平文の機密データを保存しがちなので、pentestsではroot userとして、あるいはデバイスに物理的にアクセスできる者がこのデータを盗める可能性があるためチェックする必要があります。

アプリがkeystoreにデータを保存している場合でも、データは暗号化されているべきです。

Keystore内のデータにアクセスするには、このFridaスクリプトを使用できます: https://github.com/WithSecureLabs/android-keystore-audit/blob/master/frida-scripts/tracer-cipher.js

bash
frida -U -f com.example.app -l frida-scripts/tracer-cipher.js

Fingerprint/Biometrics Bypass

以下のFrida scriptを使用すると、Androidアプリケーションがbypass fingerprint authenticationを実施して、特定の機密領域を保護する処理を回避できる可能性があります:

bash
frida --codeshare krapgras/android-biometric-bypass-update-android-11 -U -f <app.package>

Background Images

アプリをバックグラウンドに移動すると、Androidはアプリケーションのスナップショットを保存します。これによりフォアグラウンドに戻したとき、アプリ本体より先にそのイメージを読み込むため、アプリがより早く起動したように見えます。

ただし、このスナップショットに機密情報が含まれている場合、スナップショットにアクセスできる者がその情報を盗む可能性があります(アクセスするにはrootが必要である点に注意)。

スナップショットは通常次の場所に保存されます: /data/system_ce/0/snapshots

Androidは、レイアウトパラメータにFLAG_SECUREを設定することでスクリーンショットの取得を防ぐ方法を提供します。このフラグを使用すると、ウィンドウの内容がセキュアとして扱われ、スクリーンショットに表示されたり、非セキュアなディスプレイで表示されるのを防ぎます。

bash
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);

Android Application Analyzer

このツールは動的解析中の異なるツールの管理に役立ちます: https://github.com/NotSoSecure/android_application_analyzer

Intent Injection

開発者はしばしば、activities、services、broadcast receivers のようなプロキシコンポーネントを作成し、これらの Intent を処理して startActivity(...)sendBroadcast(...) のようなメソッドに渡しますが、これはリスクを伴います。

これらの Intent を誤誘導することで、攻撃者が非 export(non-exported)なアプリコンポーネントをトリガーしたり、機密性の高い content providers にアクセスしたりできる点に危険性があります。代表的な例として、WebView コンポーネントが URL を Intent.parseUri(...)Intent オブジェクトに変換して実行することで、悪意ある Intent 注入を引き起こす可能性があります。

Essential Takeaways

  • Intent Injection は web の Open Redirect 問題に類似しています。
  • 悪用は Intent オブジェクトを extras として渡すことに関係し、それらがリダイレクトされて安全でない操作を実行させる可能性があります。
  • 非-exported コンポーネントや content providers を攻撃者に晒してしまう可能性があります。
  • WebView の URL から Intent への変換により、意図しない動作が発生し得ます。

Android Client Side Injections and others

おそらくこれらの脆弱性は Web で既に知っているでしょう。Android アプリでは特に以下の点に注意してください:

  • SQL Injection: 動的クエリや Content-Providers を扱う際は、parameterized queries を使用していることを確認してください。
  • JavaScript Injection (XSS): いかなる WebViews においても JavaScript と Plugin サポートが無効になっていることを確認してください(デフォルトで無効)。 More info here.
  • Local File Inclusion: WebViews はファイルシステムへのアクセスを無効にするべきです(デフォルトでは有効) - (webview.getSettings().setAllowFileAccess(false);). More info here.
  • Eternal cookies: 多くの場合、Android アプリがセッションを終了してもクッキーが取り消されなかったり、ディスクに保存されることがあります
  • Secure Flag in cookies

Automatic Analysis

MobSF

Static analysis

アプリケーションの脆弱性評価 を使いやすい web ベースのフロントエンドで実行できます。動的解析も実行可能ですが、環境の準備が必要です。

bash
docker pull opensecurity/mobile-security-framework-mobsf
docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest

Notice that MobSF can analyse Android(apk), IOS(ipa) and Windows(apx) applications (Windows applications must be analyzed from a MobSF installed in a Windows host).
Also, if you create a ZIP file with the source code if an Android or an IOS app (go to the root folder of the application, select everything and create a ZIPfile), it will be able to analyse it also.

MobSF also allows you to diff/Compare analysis and to integrate VirusTotal (you will need to set your API key in MobSF/settings.py and enable it: VT_ENABLED = TRUE VT_API_KEY = <Your API key> VT_UPLOAD = TRUE). You can also set VT_UPLOAD to False, then the hash will be upload instead of the file.

支援付き Dynamic analysis with MobSF

MobSFAndroiddynamic analysisでも非常に有用ですが、その場合はホストにMobSFとgenymotionをインストールする必要があります(VMやDockerでは動作しません)。Note: You need to start first a VM in genymotion and then MobSF.
MobSF dynamic analyserは以下を実行できます:

  • Dump application data(URLs、ログ、clipboard、あなたが撮ったスクリーンショット、"Exported Activity Tester"が撮ったスクリーンショット、emails、SQLiteデータベース、XMLファイル、その他作成されたファイル)。これらはスクリーンショットを除き自動で行われます。スクリーンショットは撮りたいときに自分で押すか、すべてのexported activitiesのスクリーンショットを取得するには"Exported Activity Tester"を押す必要があります。
  • Capture HTTPS traffic
  • Use Frida to obtain runtime information

From android versions > 5, it will automatically start Frida and will set global proxy settings to capture traffic. It will only capture traffic from the tested application.

Frida

By default, it will also use some Frida Scripts to bypass SSL pinning, root detection and debugger detection and to monitor interesting APIs.
MobSF can also invoke exported activities, grab screenshots of them and save them for the report.

To start the dynamic testing press the green bottom: "Start Instrumentation". Press the "Frida Live Logs" to see the logs generated by the Frida scripts and "Live API Monitor" to see all the invocation to hooked methods, arguments passed and returned values (this will appear after pressing "Start Instrumentation").
MobSF also allows you to load your own Frida scripts (to send the results of your Friday scripts to MobSF use the function send()). It also has several pre-written scripts you can load (you can add more in MobSF/DynamicAnalyzer/tools/frida_scripts/others/), just select them, press "Load" and press "Start Instrumentation" (you will be able to see the logs of that scripts inside "Frida Live Logs").

Moreover, you have some Auxiliary Frida functionalities:

  • Enumerate Loaded Classes: ロードされた全てのクラスを表示します
  • Capture Strings: アプリ使用中に検出されたすべての文字列を出力します(非常にノイジー)
  • Capture String Comparisons: 非常に有用です。比較されている2つの文字列と結果がTrueかFalseかを表示します。
  • Enumerate Class Methods: クラス名(例: "java.io.File")を入力するとそのクラスの全メソッドを表示します。
  • Search Class Pattern: パターンでクラスを検索します
  • Trace Class Methods: クラス全体をTraceします(クラスの全メソッドの入力と出力を確認)。デフォルトでMobSFは複数の興味深い Android Api メソッドをトレースすることを覚えておいてください。

Once you have selected the auxiliary module you want to use you need to press "Start Intrumentation" and you will see all the outputs in "Frida Live Logs".

Shell

Mobsf also brings you a shell with some adb commands, MobSF commands, and common shell commands at the bottom of the dynamic analysis page. Some interesting commands:

bash
help
shell ls
activities
exported_activities
services
receivers

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.
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\).

Once you finish the dynamic analysis with MobSF you can press on "Start Web API Fuzzer" to fuzz http requests an look for vulnerabilities.

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:

adb shell settings put global http_proxy :0

Inspeckage を使った支援付き動的解析

You can get the tool from Inspeckage.
This tool with use some Hooks to let you know what is happening in the application while you perform a dynamic analysis.

Yaazhini

This is a great tool to perform static analysis with a GUI

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.

bash
pip3 install --user qark  # --user is only needed if not using a virtualenv
qark --apk path/to/my.apk
qark --java path/to/parent/java/folder
qark --java path/to/specific/java/file.java

ReverseAPK

  • 抽出されたすべてのファイルを表示して参照を容易にします
  • APKファイルを自動的にJavaおよびSmali形式にデコンパイルします
  • AndroidManifest.xmlを解析して一般的な脆弱性や挙動を検出します
  • 一般的な脆弱性や挙動に対する静的ソースコード解析を行います
  • デバイス情報
  • など
bash
reverse-apk relative/path/to/APP.apk

SUPER Android Analyzer

SUPERはWindows、MacOS X、Linuxで使用できるコマンドラインアプリケーションで、_.apk_ファイルを解析して脆弱性を検出します。これはAPKを展開し、一連のルールを適用して脆弱性を検出することで行います。

すべてのルールは rules.json ファイルにまとめられており、各企業やテスターは必要に応じて独自のルールを作成できます。

最新のバイナリはdownload pageからダウンロードしてください。

super-analyzer {apk_file}

StaCoAn

StaCoAn は、モバイルアプリに対して static code analysis を実施する開発者、bugbounty hunters、ethical hackers を支援する クロスプラットフォーム ツールです。

コンセプトは、モバイルアプリのファイル(.apk または .ipa ファイル)を StaCoAn アプリにドラッグ&ドロップすると、視覚的で持ち運び可能なレポートを生成する、というものです。設定やワードリストを調整してカスタマイズした体験を得ることができます。

ダウンロード latest release:

./stacoan

AndroBugs

AndroBugs Framework は、Android アプリケーションの潜在的なセキュリティ脆弱性を開発者や hackers が見つけるのを支援する脆弱性解析システムです。
Windows releases

python androbugs.py -f [APK file]
androbugs.exe -f [APK file]

Androwarn

Androwarn は、Android アプリケーションによって行われる可能性のある悪意のある振る舞いを検出し、ユーザーに警告することを主な目的としたツールです。

検出は androguard ライブラリを使用して、アプリケーションの Dalvik bytecode を Smali として表現したものに対する static analysis により行われます。

このツールは、「悪質な」アプリケーションの一般的な挙動(例: 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

MARA Framework

MARAMobile Application Reverse engineering and Analysis Framework です。一般的に使用されるモバイルアプリの reverse engineering と analysis ツールをまとめ、OWASP mobile security の脅威に対するテストを支援します。目的はモバイルアプリ開発者とセキュリティ専門家にとってこの作業をより簡単で扱いやすくすることです。

It is able to:

Koodous

マルウェア検出に有用: https://koodous.com/

Obfuscating/Deobfuscating code

Note that depending the service and configuration you use to obfuscate the code. Secrets may or may not ended obfuscated.

ProGuard

From Wikipedia: 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.

DexGuard

Find a step-by-step guide to deobfuscate the apk in https://blog.lexfo.fr/dexguard.html

(From that guide) Last time we checked, the Dexguard mode of operation was:

  • load a resource as an InputStream;
  • feed the result to a class inheriting from FilterInputStream to decrypt it;
  • do some useless obfuscation to waste a few minutes of time from a reverser;
  • feed the decrypted result to a ZipInputStream to get a DEX file;
  • finally load the resulting DEX as a Resource using the loadDex method.

DeGuard

DeGuard reverses the process of obfuscation performed by Android obfuscation tools. This enables numerous security analyses, including code inspection and predicting libraries.

You can upload an obfuscated APK to their platform.

[Deobfuscate android App]https://github.com/In3tinct/deobfuscate-android-app

This is a LLM tool to find any potential security vulnerabilities in android apps and deobfuscate android app code. Uses Google's Gemini public API.

Simplify

It is a generic android deobfuscator. Simplify virtually executes an app to understand its behavior and then tries to optimize the code so it behaves identically but is easier for a human to understand. Each optimization type is simple and generic, so it doesn't matter what the specific type of obfuscation is used.

APKiD

APKiD gives you information about how an APK was made. It identifies many compilers, packers, obfuscators, and other weird stuff. It's PEiD for Android.

Manual

チュートリアルを読んで how to reverse custom obfuscation のいくつかの技を学んでください

Labs

Androl4b

AndroL4b is an Android security virtual machine based on ubuntu-mate includes the collection of latest framework, tutorials and labs from different security geeks and researchers for reverse engineering and malware analysis.

References

tip

AWSハッキングを学び、実践する:HackTricks Training AWS Red Team Expert (ARTE)
GCPハッキングを学び、実践する:HackTricks Training GCP Red Team Expert (GRTE) Azureハッキングを学び、実践する:HackTricks Training Azure Red Team Expert (AzRTE)

HackTricksをサポートする