📅  最后修改于: 2023-12-03 15:24:36.112000             🧑  作者: Mango
SQL注入是最常见的网络攻击之一,它利用应用程序未对用户输入的数据进行充分过滤而导致恶意代码被插入到SQL语句中,从而实现攻击。为此,我们可以使用Python编程语言构建一个SQL注入扫描器来检测并防范SQL注入攻击。
在开始编写扫描器代码之前,您需要安装以下软件包:
import re
import argparse
import requests
import MySQLdb
from bs4 import BeautifulSoup
使用argparse库来解析命令行参数,这样我们就可以从命令行中获取url和cookie。
parser = argparse.ArgumentParser(description='SQL Injection Scanner')
parser.add_argument('-u', dest='url', type=str, required=True,
help='URL to scan for SQL Injection vulnerabilities')
parser.add_argument('-c', dest='cookie', type=str, required=False,
help='Cookie value')
args = parser.parse_args()
在编写实际的SQL注入脚本之前,我们首先需要检查是否可以连接到指定的网站并从中提取数据。
def connect(url, cookie=None):
headers = {}
if cookie:
headers['Cookie'] = cookie
try:
response = requests.get(url, headers=headers)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
return soup
except Exception as e:
print("[-] Connection Error", str(e))
在检查连接后,我们需要从HTML页面中提取表单,并为找到的每个表单构造完整的URL。我们可以使用BeautifulSoup库来从HTML页面中提取表单。
def get_all_forms(soup):
return soup.find_all('form')
def get_form_details(form):
details = {}
try:
action = form.attrs.get('action').lower()
except:
action = None
inputs = form.find_all('input')
for input in inputs:
name = input.attrs.get('name')
value = input.attrs.get('value')
if name is not None:
details[name] = value
return action, details
def get_urls(soup, url):
urls = []
for form in get_all_forms(soup):
action, details = get_form_details(form)
if action is None:
action = url
elif action[:4] == 'http':
pass
else:
action = url + '/' + action
urls.append({'url': action, 'data': details})
return urls
在得到URL和表单之后,我们需要开始构造请求并发送它们。通过使用requests库,我们可以模拟提交表单和发送数据。
def send_request(url, data, cookie=None):
headers = {}
if cookie:
headers['Cookie'] = cookie
try:
if data:
response = requests.post(url, data=data, headers=headers)
else:
response = requests.get(url, headers=headers)
return response
except Exception as e:
print("[-] Request Error", str(e))
现在,我们可以开始检测SQL注入了。在这里,我们将使用正则表达式来检测错误消息并确定数据库是否容易受到SQL注入攻击。
def check_injection(response, url, data):
errors = {"You have an error in your SQL syntax;",
"Warning: mysql_",
"Unclosed quotation mark after the character string",
"Evaluation of the query resulted in an error",
"mysql_fetch"}
for error in errors:
if error in response.content.decode().lower():
print(f"[+] SQL Injection vulnerability detected on {url}")
print(f"[+] Payload: {data}\n")
return True
return False
最后,我们需要运行我们编写的扫描器程序。
def main():
soup = connect(args.url, args.cookie)
urls = get_urls(soup, args.url)
for url in urls:
url = url['url']
data = url['data']
response = send_request(url, data, args.cookie)
if response:
check_injection(response, url, data)
我们已经创建了一个Python程序来扫描SQL注入漏洞。当使用这个程序时,记住要使用它来检查自己的网站和应用程序,因为SQL注入攻击是最常见的攻击之一。