Python:mitmproxy获取HTTP请求URL

import mitmproxy.http
import logging,sys

logging.basicConfig(filename=sys.path[0]+'/'+__name__+'.log',format='[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]', level=logging.INFO,filemode='a',datefmt='%Y-%m-%d%I:%M:%S %p')

# http static resource file extension
static_ext = ['js', 'css', 'ico', 'jpg', 'png', 'gif', 'jpeg', 'bmp', 'conf']
# media resource files type
media_types = ['image', 'video', 'audio']

# url filter
url_filter = ['www.baidu.com','m.baidu.com','mbd.baidu.com','www.google.com','www.qq.com','www.youku.com','h5.dingtalk.com']

word_filter = ['json','JSON','login','error']

static_files = [
    'text/css',
    'image/jpeg',
    'image/gif',
    'image/png',
]


# 词过滤
def wordFilter(url):
    flag = False
    for word in word_filter:
        if url.__contains__(word):
            flag = True
            break
    return flag


class HttpFilter:
    def response(self, flow: mitmproxy.http.HTTPFlow):
        # 忽略相应的地址
        host = flow.request.host
        if host in url_filter:
            return

        if not flow.request.method == "GET":
            return

        if not flow.response.status_code == 200:
            return

        # 忽略相应的请求
        url = flow.request.url
        if wordFilter(url):
            return
        lastPath = url.split('?')[0].split('/')[-1]
        if lastPath.split('.')[-1] in static_ext:
            return

        if flow.response.text.__contains__('<html'):
            logging.info(flow.request.pretty_url)


addons = [
    HttpFilter()
]

 

<think>我们使用mitmproxy的addon功能来拦截并修改HTTP POST请求的JSON数据。主要步骤包括: 1. 创建一个mitmproxy的addon类 2. 在`request`方法中过滤POST请求 3. 检查请求头中的Content-Type是否为application/json 4. 解析请求体中的JSON数据 5. 修改JSON数据 6. 将修改后的JSON数据重新设置为请求体 注意:修改请求体后,需要更新Content-Length头部,因为请求体的长度可能发生了变化。mitmproxy会自动处理这个,但为了确保正确,我们可以手动更新。 以下是一个示例addon,它将捕获所有POST请求,如果请求体是JSON,则在JSON中添加一个字段`"injected": true`,并打印修改前后的内容。 创建文件`modify_post_json.py`,内容如下:</think>### 使用 Python3 和 mitmproxy 修改 HTTP POST 请求中的 JSON 数据 以下是完整的实现方案,通过创建 mitmproxy 插件拦截并修改 POST 请求中的 JSON 内容: ```python from mitmproxy import http, ctx import json class JsonModifier: def request(self, flow: http.HTTPFlow): # 只处理 POST 请求 if flow.request.method != "POST": return # 检查是否为 JSON 数据 content_type = flow.request.headers.get("Content-Type", "").lower() if "application/json" not in content_type: ctx.log.warn(f"⚠️ 非JSON请求: {flow.request.url}") return try: # 解析 JSON 请求体 original_body = flow.request.content.decode('utf-8') json_data = json.loads(original_body) ctx.log.info(f"🔥 捕获 JSON POST: {flow.request.url}") # 显示原始数据 ctx.log.info(f"📦 原始数据:\n{json.dumps(json_data, indent=2)}") # ✨ 修改 JSON 数据(示例) # 1. 添加新字段 json_data["injected"] = True # 2. 修改现有字段(示例:修改用户ID) if "user_id" in json_data: json_data["user_id"] = "MODIFIED_" + json_data["user_id"] # 3. 删除敏感字段(示例) if "password" in json_data: del json_data["password"] # 将修改后的数据写回请求 modified_body = json.dumps(json_data).encode('utf-8') flow.request.content = modified_body # 更新内容长度(重要!) flow.request.headers["Content-Length"] = str(len(modified_body)) # 显示修改结果 ctx.log.info(f"🛠️ 修改后数据:\n{json.dumps(json_data, indent=2)}") ctx.log.info("━" * 50) except Exception as e: ctx.log.error(f"❌ JSON解析失败: {str(e)}") addons = [JsonModifier()] ``` #### 实现步骤说明: 1. **创建插件类**: ```python class JsonModifier: def request(self, flow: http.HTTPFlow): ``` 2. **过滤 POST 请求**: ```python if flow.request.method != "POST": return ``` 3. **检查 JSON 类型**: ```python content_type = flow.request.headers.get("Content-Type", "").lower() if "application/json" not in content_type: return ``` 4. **解析并修改 JSON**: ```python json_data = json.loads(original_body) # 解析原始数据 json_data["injected"] = True # 添加新字段 ``` 5. **更新请求内容**: ```python flow.request.content = modified_body # 写入修改后的数据 flow.request.headers["Content-Length"] = str(len(modified_body)) # 更新长度 ``` #### 启动命令: ```bash mitmdump -s modify_post_json.py ``` #### 典型应用场景: 1. **API 测试**:修改请求参数测试边界条件 2. **安全测试**:删除敏感字段或添加测试标记 3. **数据脱敏**:自动替换敏感信息 4. **功能调试**:模拟特定数据场景 #### 高级修改示例: ```python # 条件修改:仅针对特定URL if "api.example.com" in flow.request.url: if "amount" in json_data: json_data["amount"] *= 2 # 交易金额翻倍 # 正则匹配修改 import re if re.search(r"/user/\d+/update", flow.request.url): json_data["role"] = "admin" # 提升权限 ``` #### 注意事项: 1. **HTTPS 支持**:需安装 mitmproxy CA 证书 2. **内容长度**:修改后必须更新 `Content-Length` 头 3. **错误处理**:添加异常捕获防止解析失败 4. **性能影响**:复杂操作可能降低代理速度 > 此方案可实时拦截并修改经过代理的所有 JSON POST 请求,适用于API测试、安全审计和数据脱敏等场景[^1]。 --- ### 相关问题 1. 如何只修改特定域名的 POST 请求? 2. 怎样在修改后自动保存原始和修改后的请求? 3. mitmproxy 如何处理二进制 POST 数据? 4. 能否同时修改请求头和请求体? 5. 如何将修改后的请求转发到不同服务器?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值