问题背景
做渗透测试时发现漏洞需要把现场转换为curl,方便开发导入postman或者服务器直接执行,快速定位问题。可以利用用第三方类库curlify将Python的requests请求转换为CURL命令。
import curlify
import requests
data = {"key": "value"}
url = "http://example.com/api"
headers = {"Content-type": "application/json"}
response = requests.post(url, headers=headers, json=data)
curl_command = curlify.to_curl(response.request)
print(curl_command)
但是此代码仅适用于requests库中的HTTP请求。如果想灵活组装request,就需要对算法进行改造。
具体代码
安装格式组装即可,适用于如mitmproxy
{
"scheme": "",
"host": "",
"path": "",
"method": "",
"headers": "",
"req_query": {},
"req_body": {},
"req_form": {},
"res_body": {}
}
def to_curl(request, verify=True): # compressed=False,
"""
转化为curl
"""
# 提取需要的信息
method = request['method']
req_query = request['req_query']
req_body = request['req_body']
req_form = request['req_form']
headers = request['headers']
# 处理内容长度
if 'content-length' in headers:
del headers['content-length']
# 拼接请求地址
url = request['scheme'] + "://" + request['host'] + request['path']
# 获取请求体格式
if 'content-type' in headers.keys():
content_type = headers['content-type']
else:
content_type = ''
# 组装基本模型
parts = [
('curl', None),
('-X', method),
]
# 遍历拼接headers
for k, v in sorted(headers.items()):
parts += [('-H', '{0}: {1}'.format(k, v))]
# 先处理query参数
if len(req_query) != 0:
# 拼接在url后面 json需要转化为xx=xx&xx=xx
url = url + '?' + urlencode(req_query)
# 拼接url
parts += [(None, url)]
# 拼接请求体
# 处理post中的2种请求体
if method == 'POST':
if content_type == 'application/x-www-form-urlencoded':
# 从json转化为表单
body = urlencode(req_form)
parts += [('-d', body)]
elif content_type in( 'application/json','content_type == 'application/json;charset=UTF-8', 'content_type == 'application/json; charset=utf-8'):
# 转化字符串
body = json.dumps(req_body)
parts += [('-d', body)]
# if compressed:
parts += [('--compressed', url)]
if not verify:
parts += [('--insecure', None)]
# 拼接,并且转化为双引号
flat_parts = []
for k, v in parts:
if k:
flat_parts.append(quote(k))
if v:
flat_parts.append(quote(v))
# 按空格拼接元祖
target_curl = ' '.join(flat_parts)
# print(target_curl)
return target_curl
效果
curl -X POST -H 'accept: application/json, text/plain, */*' -H 'xx''https://xxx/1.0.0 -d '{"xx": "xx"}' --compressed https://xxx/1.0.0