python 代碼審計-命令執行漏洞(自己編寫的代碼)
阿新 • • 發佈:2018-09-10
[1] 問題 錯誤 code 端口掃描 iter turn command att python 代碼審計-命令執行漏洞(自己編寫的代碼)
0x00 源代碼
def execute(request): context ={} ip= request.POST.get("ip") username= request.POST.get("username") password= request.POST.get("password") idnex= int(request.POST.get("index")) current_time=request.POST.get("time") context = {"ip":ip,"username":username,"password":password,"result":False} ippattern="(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\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) return HttpResponse(json.dumps(context)) try: length,scripts=executeScript.getScriptNums() if(idnex>length or idnex<1): context[‘error‘]="腳本索引值錯誤" log("error","[-]%s %s %s Script index value error"%(ip,str(length),str(index))) print ("[-]%s %s %s 腳本索引值錯誤"%(ip,str(length),str(index))) return HttpResponse(json.dumps(context)) script=scripts[idnex-1] #判斷是否是端口掃描 if("port_scan" in script): current_path=os.getcwd() payload="python %s//jixianjiancha/check/%s %s"%(current_path,script,ip) commandResult=commands.getoutput(payload) result=ast.literal_eval(commandResult)
0x01 代碼執行漏洞原因分析
第一步:獲取前臺傳入的ip: ip= request.POST.get("ip")
第二步:判斷輸入的ip是否合法
ippattern="(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d).(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d).(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d).(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\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="python %s//jixianjiancha/check/%s %s"%(current_path,script,ip)
commandResult=commands.getoutput(payload)
將判斷後的ip直接拼接到payload中,然後使用commands命令執行函數執行命令
由於ip過濾不嚴格,所以會造成任意命令執行漏洞
0x02 修復方案
修復改問題主要是要嚴格過濾ip,因此將ip以‘.‘分割成4份,判斷每一份是否是數字,如果不是全是則表名輸入的ip不合法。
ip= request.POST.get("ip") testip=ip.split(".") if(testip[0].isdigit() and testip[1].isdigit() and testip[2].isdigit()and testip[3].isdigit()): pass else: context[‘error‘]="ip格式不正確" log("error","[-] %s ip is error"%(ip))
python 代碼審計-命令執行漏洞(自己編寫的代碼)