如何在Python中构建SQL注入扫描器?代码实现指南

2021年11月16日14:58:31 发表评论 1,647 次浏览

Python如何构建SQL注入扫描器?本文带你了解如何使用 Python 中的请求和 BeautifulSoup 编写一个简单的 Python 脚本来检测 Web 应用程序上的 SQL 注入漏洞。

SQL 注入是一种代码注入技术,用于通过用户输入数据对易受攻击的 Web 应用程序执行 SQL 查询。它是最常见和最危险的网络黑客技术之一。

成功的 SQL 注入攻击通常会对数据库和 Web 应用程序造成大量有害损害。例如,它可以从数据库中读取用户密码等敏感数据,插入、修改甚至删除数据。

如何在Python中构建SQL注入扫描器?在本教程中,你将学习如何构建一个简单的 Python 脚本来检测 Web 应用程序中的 SQL 注入漏洞。

让我们为本教程安装所需的库:

pip3 install requests bs4

让我们导入必要的模块:

import requests
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin
from pprint import pprint

# initialize an HTTP session & set the browser
s = requests.Session()
s.headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36"

我们还初始化了一个请求会话并设置了用户代理。

Python构建SQL注入扫描器示例:由于 SQL 注入与用户输入有关,因此我们首先需要提取 Web 表单。幸运的是,我已经写了一篇关于在 Python 中提取和填写表单的教程,我们需要以下函数:

def get_all_forms(url):
    """Given a `url`, it returns all forms from the HTML content"""
    soup = bs(s.get(url).content, "html.parser")
    return soup.find_all("form")


def get_form_details(form):
    """
    This function extracts all possible useful information about an HTML `form`
    """
    details = {}
    # get the form action (target url)
    try:
        action = form.attrs.get("action").lower()
    except:
        action = None
    # get the form method (POST, GET, etc.)
    method = form.attrs.get("method", "get").lower()
    # get all the input details such as type and name
    inputs = []
    for input_tag in form.find_all("input"):
        input_type = input_tag.attrs.get("type", "text")
        input_name = input_tag.attrs.get("name")
        input_value = input_tag.attrs.get("value", "")
        inputs.append({"type": input_type, "name": input_name, "value": input_value})
    # put everything to the resulting dictionary
    details["action"] = action
    details["method"] = method
    details["inputs"] = inputs
    return details

get_all_forms()使用BeautifulSoup库提取从HTML并返回所有这些形式的标签,Python列表,而get_form_details()函数获得一个单一的形式标签对象作为参数,并解析关于形式的有用信息,例如动作(目标URL),方法(GETPOST,等)和所有输入字段属性(type,namevalue)。

Python如何构建SQL注入扫描器?接下来,我们定义一个函数来告诉我们一个网页是否有 SQL 错误,这在检查 SQL 注入漏洞时会很方便:

def is_vulnerable(response):
    """A simple boolean function that determines whether a page 
    is SQL Injection vulnerable from its `response`"""
    errors = {
        # MySQL
        "you have an error in your sql syntax;",
        "warning: mysql",
        # SQL Server
        "unclosed quotation mark after the character string",
        # Oracle
        "quoted string not properly terminated",
    }
    for error in errors:
        # if you find one of these errors, return True
        if error in response.content.decode().lower():
            return True
    # no error detected
    return False

显然,我无法为所有数据库服务器定义错误,为了更可靠的检查,你需要使用正则表达式来查找错误匹配,检查这个包含很多错误匹配的XML 文件(由sqlmap实用程序使用)。

如何在Python中构建SQL注入扫描器?现在我们有了所有的工具,让我们定义主要功能,它搜索网页中的所有表单并尝试在输入字段中放置引号和双引号字符,Python构建SQL注入扫描器示例:

def scan_sql_injection(url):
    # test on URL
    for c in "\"'":
        # add quote/double quote character to the URL
        new_url = f"{url}{c}"
        print("[!] Trying", new_url)
        # make the HTTP request
        res = s.get(new_url)
        if is_vulnerable(res):
            # SQL Injection detected on the URL itself, 
            # no need to preceed for extracting forms and submitting them
            print("[+] SQL Injection vulnerability detected, link:", new_url)
            return
    # test on HTML forms
    forms = get_all_forms(url)
    print(f"[+] Detected {len(forms)} forms on {url}.")
    for form in forms:
        form_details = get_form_details(form)
        for c in "\"'":
            # the data body we want to submit
            data = {}
            for input_tag in form_details["inputs"]:
                if input_tag["type"] == "hidden" or input_tag["value"]:
                    # any input form that is hidden or has some value,
                    # just use it in the form body
                    try:
                        data[input_tag["name"]] = input_tag["value"] + c
                    except:
                        pass
                elif input_tag["type"] != "submit":
                    # all others except submit, use some junk data with special character
                    data[input_tag["name"]] = f"test{c}"
            # join the url with the action (form request URL)
            url = urljoin(url, form_details["action"])
            if form_details["method"] == "post":
                res = s.post(url, data=data)
            elif form_details["method"] == "get":
                res = s.get(url, params=data)
            # test whether the resulting page is vulnerable
            if is_vulnerable(res):
                print("[+] SQL Injection vulnerability detected, link:", url)
                print("[+] Form:")
                pprint(form_details)
                break

在提取表单并提交之前,上述函数首先检查 URL 中的漏洞,因为 URL 本身可能存在漏洞,这只需在 URL 后附加引号即可完成。

然后我们使用requests库发出请求并检查响应内容是否有我们正在搜索的错误。

Python构建SQL注入扫描器示例:之后,我们解析表单并在找到的每个表单上使用引号字符提交,这是我在已知易受攻击的网页上测试后运行的结果:

if __name__ == "__main__":
    url = "http://testphp.vulnweb.com/artists.php?artist=1"
    scan_sql_injection(url)

输出:

[!] Trying http://testphp.vulnweb.com/artists.php?artist=1"
[+] SQL Injection vulnerability detected, link: http://testphp.vulnweb.com/artists.php?artist=1"

如何在Python中构建SQL注入扫描器?正如你所看到的,这在 URL 本身中很容易受到攻击,但是在我在本地易受攻击的服务器 ( DVWA )上对此进行测试后,我得到了以下输出:

[!] Trying http://localhost:8080/DVWA-master/vulnerabilities/sqli/"
[!] Trying http://localhost:8080/DVWA-master/vulnerabilities/sqli/'
[+] Detected 1 forms on http://localhost:8080/DVWA-master/vulnerabilities/sqli/.
[+] SQL Injection vulnerability detected, link: http://localhost:8080/DVWA-master/vulnerabilities/sqli/
[+] Form:
{'action': '#',
 'inputs': [{'name': 'id', 'type': 'text', 'value': ''},
            {'name': 'Submit', 'type': 'submit', 'value': 'Submit'}],
 'method': 'get'}

注意: 如果你想在本地易受攻击的 Web 应用程序(如DVWA )上测试脚本,则需要先登录,我在此处的脚本中提供了登录 DVWA 的代码 ,你可以在此处找到它作为注释代码开始。

结论

请注意,我已经在许多易受攻击的网站上测试了此脚本,并且运行良好。但是,如果你想要更可靠的 SQL 注入工具,请考虑使用sqlmap,它也是用 Python 语言编写的,它可以自动检测和利用 SQL 注入缺陷的过程。

Python如何构建SQL注入扫描器?你可以通过添加漏洞利用功能来扩展此代码,此备忘单可以帮助你使用正确的 SQL 命令。或者你可能想提取所有网站链接并检查所有网站页面上的漏洞,你也可以这样做!

最后,尝试以合乎道德的方式使用此代码,我们不对任何滥用此代码的行为负责!

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: