python如何实现代码审计-创新互联

这篇文章给大家分享的是有关python如何实现代码审计的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

创新互联建站专注于南郑企业网站建设,响应式网站建设,商城网站制作。南郑网站建设公司,为南郑等地区提供建站服务。全流程按需搭建网站,专业设计,全程项目跟踪,创新互联建站专业和态度为您提供的服务

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如何实现代码审计”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享名称:python如何实现代码审计-创新互联
URL网址:http://myzitong.com/article/dhsccp.html