python 代码审计 命令执行漏洞 (自己编写的代码)
0x00 源代码defexecute(request):
context={}
ip=request.POST.get("ip")
username=request.POST.get("username")
password=request.POST.get("password")
idnex=int(request.POST.get("index"))
currenttime=request.POST.get("time")
context={"ip":ip,"username":username,"password":password,"result":False}
ippattern="(25[05]|2[04]\d|[01]\d{2}|[19]\d)\.(25[05]|2[04]\d|[01]\d{2}|[19]\d)\.(25[05]|2[04]\d|[01]\d{2}|[19]\d)\.(25[05]|2[04]\d|[01]\d{2}|[19]\d)"
if(re.match(ippattern,ip)):
pass
else:
context['error']="ip 格式不正确"
log("error","[]%s ip is error"%(ip))
print("[]%s ip 格式不正确"%(ip))
#return render(request, 'test.html', context)
returnHttpResponse(json.dumps(context))
try:
length,scripts=executeScript.getScriptNums()
if(idnex>lengthoridnex<1):
context[&#39;error&#39;]&#61;"脚本索引值错误"
log("error","[]%s %s %s Script index value error"%(ip,str(length),str(index)))
print("[]%s %s %s 脚本索引值错误"%(ip,str(length),str(index)))
returnHttpResponse(json.dumps(context))
script&#61;scripts[idnex1]
#判断是否是端口扫描
if("portscan"inscript):
currentpath&#61;os.getcwd()
payload&#61;"python %s//jixianjiancha/check/%s %s"%(currentpath,script,ip)
commandResult&#61;commands.getoutput(payload)
result&#61;ast.literaleval(commandResult)
0x01 代码执行漏洞原因分析
第一步: 获取前台传入的 ip: ip&#61; request.POST.get("ip")
第二步: 判断输入的 ip 是否合法ippattern&#61;"(25[05]|2[04]\d|[01]\d{2}|[19]\d).(25[05]|2[04]\d|[01]\d{2}|[19]\d).(25[05]|2[04]\d|[01]\d{2}|[19]\d).(25[05]|2[04]\d|[01]\d{2}|[19]\d)"
if(re.match(ippattern,ip)):
pass
else:
这段代码仔细一看, 只是判断了 ip 是否以正常 ip 开头, 比如 12.12.121.12, 只要是以正常 ip 开头的, 就可以通过 ip 的检测. 比如输入的 ip 为: 127.0.0.1; ping c 1 127.0.0.1
第三步:payload&#61;"python %s//jixianjiancha/check/%s %s"%(currentpath,script,ip)
commandResult&#61;commands.getoutput(payload)
将判断后的 ip 直接拼接到 payload 中, 然后使用 commands 命令执行函数执行命令
由于 ip 过滤不严格, 所以会造成任意命令执行漏洞
0x02 修复方案
修复改问题主要是要严格过滤 ip, 因此将 ip 以&#39;.&#39;分割成 4 份, 判断每一份是否是数字, 如果不是全是则表名输入的 ip 不合法.ip&#61;request.POST.get("ip")
testip&#61;ip.split(".")
if(testip[0].isdigit()andtestip[1].isdigit()andtestip[2].isdigit()andtestip[3].isdigit()):
pass
else:
context[&#39;error&#39;]&#61;"ip 格式不正确"
log("error","[] %s ip is error"%(ip))
来源: http://www.bubuko.com/infodetail-2762343.html