使用MITMProxy轉發請求到本地、儲存鑑權給本地請求

timseng發表於2024-06-27

背景:

1.公司專案,沒有前端專案,無法起前端,無法驗證本地介面

2.介面鑑權OATH2,使用postman除錯每次都要取瀏覽器複製Authorization頭,還會頻繁過期,影響效率

方案:使用MITMProxy自定義流量處理

MITMProxy是一種用於中間人攻擊(Man-in-the-middle attack)的代理工具。它的作用是在正常的代理功能基礎上,截獲、記錄或篡改資料,並自定義特定的行為。與其他抓包工具(如Fiddler或Wireshark)不同的是,MITMProxy不僅可以檢視和分析截獲的請求,還可以透過自定義指令碼進行二次開發。例如,可以截獲瀏覽器對特定URL的請求,將返回內容置空並儲存真實的返回內容到資料庫,並在出現異常時傳送郵件通知。與Fiddler類似的需求無法實現高度定製化,而MITMProxy可透過載入自定義Python指令碼輕鬆實現。

安裝:brew install mitmproxy

指令碼:

# mitmproxy script to intercept and modify requests
from mitmproxy import http
import os

TOKEN_FILE_PATH = "/Users/xy/workspace/python/mitmproxy/token_file.txt"
LOG_FILE_PATH = "/Users/xy/workspace/python/mitmproxy/log_file.txt"


def save_log_to_file(log):
    with open(LOG_FILE_PATH, "a") as file:
        file.writelines(log+"\n")

def save_token_to_file(token):
    with open(TOKEN_FILE_PATH, "w") as file:
        file.write(token)

def load_token_from_file():
    if os.path.exists(TOKEN_FILE_PATH):
        with open(TOKEN_FILE_PATH, "r") as file:
            token = file.read().strip()
            return token
    return None

def request(flow: http.HTTPFlow) -> None:

    #儲存dev的鑑權
    # Check if the host is a.com and save the token
    if "dev-oa.xx.com" in flow.request.pretty_host:
        save_log_to_file('---->dev-oa.xx.com')
        token = flow.request.headers.get("Authorization")
        if token:
            save_log_to_file('save token')
            save_log_to_file(token)
            save_token_to_file(token)
        # Modify the request URL to dev_a.com
        # flow.request.host = "dev_a.com"
    # Check if the host is b.com and inject the token
            
    #使用儲存的鑑權覆蓋本地的請求
    elif "127.0.0.1" in flow.request.pretty_host:
        save_log_to_file('---->127.0.0.1')
        token = load_token_from_file()
        if token:
            save_log_to_file('token')
            save_log_to_file(token)
            flow.request.headers["Authorization"] = token

    #將dev的前端請求轉發給本地
    # Replace dev-oa.xx.com/flow with 127.0.0.1:9099
    if "dev-oa.xx.com/flow/h5" in flow.request.pretty_url or "dev-oa.xx.com/flow/admin" in flow.request.pretty_url:
    # if False:
        flow.request.host = "127.0.0.1"
        flow.request.port = 9099
        flow.request.scheme = "http"
        flow.request.path = flow.request.path.replace("/flow", "",1)

啟動:mitmproxy -s modify_request.py -p 8089

注意那兩個檔案的許可權

然後在系統設定代理 127.0.0.1 8089

相關文章