在 python 中发送 application/x-protobuf 文件
sending application/x-protobuf file in python
我正在编写一个 mitmproxy 脚本来拦截 application/x-protobuf 文件并进行一些修改,然后将其转发给客户端。
这是代码:
from cStringIO import StringIO
from libmproxy.protocol.http import decoded
import re
def response(context, flow):
if flow.response.headers.get_first("content-type", "").startswith('application/x-protobuf'):
with decoded(flow.response):
data=flow.response.content
data2=re.sub('"http://.*?"','"http://some other url"' ,data)
flow.response.content=data2
然而,当客户端收到文件时,它会抛出 "Failed to parse input." 错误
这看起来像问题:
re.sub('"http://.*?"','"http://some other url"' ,data)
您不能使用正则表达式重写嵌入在 protobuf 中的 URL。 Protobuf 是一种使用基于长度的分隔符的二进制编码。因此,例如,当一个字符串嵌入到 protobuf 中时,它会以长度为前缀。如果您使用正则表达式更改字符串,则长度将是错误的。请注意,您不能只更改长度,因为父对象的长度可能仍然是错误的,等等。
您需要使用 Protobuf Python 库解码 protobuf 数据,编辑您需要更改的字段,然后重新编码。
我正在编写一个 mitmproxy 脚本来拦截 application/x-protobuf 文件并进行一些修改,然后将其转发给客户端。 这是代码:
from cStringIO import StringIO
from libmproxy.protocol.http import decoded
import re
def response(context, flow):
if flow.response.headers.get_first("content-type", "").startswith('application/x-protobuf'):
with decoded(flow.response):
data=flow.response.content
data2=re.sub('"http://.*?"','"http://some other url"' ,data)
flow.response.content=data2
然而,当客户端收到文件时,它会抛出 "Failed to parse input." 错误
这看起来像问题:
re.sub('"http://.*?"','"http://some other url"' ,data)
您不能使用正则表达式重写嵌入在 protobuf 中的 URL。 Protobuf 是一种使用基于长度的分隔符的二进制编码。因此,例如,当一个字符串嵌入到 protobuf 中时,它会以长度为前缀。如果您使用正则表达式更改字符串,则长度将是错误的。请注意,您不能只更改长度,因为父对象的长度可能仍然是错误的,等等。
您需要使用 Protobuf Python 库解码 protobuf 数据,编辑您需要更改的字段,然后重新编码。