Androidアプリの通信内容を確認したいときがある。
便利なライブラリや、仕方なく組み込んだSDKにより、Androidの実際の通信内容をすべて把握することは難しい。
そんなあなたに mitmproxy
Charlesと違い無料だ。使い放題しろ
インストール
brew install mitmproxy
起動
PCで実行
mitmproxy
接続
Androidのプロキシの設定をする。
https://shnk38.com/android/how-to-android/f5321-wi-fi-proxy/
- IPアドレスはPCのもの。 ifconfigコマンドで参照できるやつ
- ポートは8080
証明書のインストール
プロキシの設定が正しく行えていれば、Androidのブラウザで mitm.it にアクセスすると、証明書のインストールができる。
Android 7 以降での注意点
Android Nougat changes how applications interact with user- and admin-supplied CAs. By default, apps that target API level 24 will—by design—not honor such CAs unless the app explicitly opts in.
https://android-developers.googleblog.com/2016/07/changes-to-trusted-certificate.html
ここで諸君に残念なお知らせだ。
Android 7 以降の端末では、巷にあふれるイカしたアプリのSSL/TLSを用いた通信を覗き見ることはできない。なぜなら上記でインストールした証明書を参照してくれないからだ。
自分のアプリの場合は、以下の手順で証明書を参照するように設定できる。
src/main/res/xml/network_security_config.xml を作成。
<network-security-config>
     <debug-overrides>
          <trust-anchors>
               <certificates src="user" />
          </trust-anchors>
     </debug-overrides>
</network-security-config>
AndroidManifest.xml に以下を追加。
     <application
        <!-- 追加 -->
        android:networkSecurityConfig="@xml/network_security_config"
よく使うコマンド
- 中を見たい通信をえらんで enter。Response<->Request<->Detailタブの切替はtab。
- shift-fで追従モード切り替え
- zで全部消す
- fでフィルタ設定
レスポンスの変更
レスポンスをPCに用意したtxtファイルの中身に置き換えたい、というようなことはあると思う。しかし、Charles と違いUIでポチポチ設定できない。
例えば http://example.com/hoge?q=anything のレスポンス結果をクエリパラメータによらず hoge.txt の中身に置き換えたいとしよう。
hoge.py に以下を書く。( mitmproxy v2.0.2 )
class Replacer:
    def response(self, flow):
        if flow.request.pretty_url.startswith("http://example.com/hoge"):
            with open("hoge.txt", "r") as file:
                flow.response.text = file.read()
                
def start():
    return Replacer()
そして、起動時のパラメータに付与する。
mitmproxy -s hoge.py
