#!/usr/bin/env python

"""
Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""

import os
import random

# 导入lib.core.common模块中的singleTimeWarnMessage函数
from lib.core.common import singleTimeWarnMessage
# 导入lib.core.compat模块中的xrange函数
from lib.core.compat import xrange
# 导入lib.core.enums模块中的DBMS枚举
from lib.core.enums import DBMS
# 导入lib.core.enums模块中的PRIORITY枚举
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.LOW

# 定义一个函数，用于检查脚本依赖
def dependencies():
    # 输出警告信息，说明该脚本只能用于特定数据库
    singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s" % (os.path.basename(__file__).split(".")[0], DBMS.MSSQL))

def tamper(payload, **kwargs):
    """
    Replaces (MsSQL) instances of space character (' ') with a random blank character from a valid set of alternate characters

    Requirement:
        * Microsoft SQL Server

    Tested against:
        * Microsoft SQL Server 2000
        * Microsoft SQL Server 2005

    Notes:
        * Useful to bypass several web application firewalls

    >>> random.seed(0)
    >>> tamper('SELECT id FROM users')
    'SELECT%0Did%0DFROM%04users'
    """

    # ASCII table:
    #   SOH     01      start of heading
    #   STX     02      start of text
    #   ETX     03      end of text
    #   EOT     04      end of transmission
    #   ENQ     05      enquiry
    #   ACK     06      acknowledge
    #   BEL     07      bell
    #   BS      08      backspace
    #   TAB     09      horizontal tab
    #   LF      0A      new line
    #   VT      0B      vertical TAB
    #   FF      0C      new page
    #   CR      0D      carriage return
    #   SO      0E      shift out
    #   SI      0F      shift in
    # 定义一个元组，包含一些字符串
    blanks = ('%01', '%02', '%03', '%04', '%05', '%06', '%07', '%08', '%09', '%0B', '%0C', '%0D', '%0E', '%0F', '%0A')
    # 将payload赋值给retVal
    retVal = payload

    if payload:
        retVal = ""
        quote, doublequote, firstspace, end = False, False, False, False

        # 遍历payload中的每个字符
        for i in xrange(len(payload)):
            # 如果当前字符不是空格，则将firstspace设置为True
            if not firstspace:
                if payload[i].isspace():
                    firstspace = True
                    # 在retVal中添加一个随机选择的空格
                    retVal += random.choice(blanks)
                    continue

            # 如果当前字符是单引号，则将quote取反
            elif payload[i] == '\'':
                quote = not quote

            # 如果当前字符是双引号，则将doublequote取反
            elif payload[i] == '"':
                doublequote = not doublequote

            # 如果当前字符是#或者--，则将end设置为True
            elif payload[i] == '#' or payload[i:i + 3] == '-- ':
                end = True

            # 如果当前字符是空格，且不是在双引号或单引号中，则根据end的值添加一个随机选择的空格
            elif payload[i] == " " and not doublequote and not quote:
                if end:
                    retVal += random.choice(blanks[:-1])
                else:
                    retVal += random.choice(blanks)

                continue

            # 将当前字符添加到retVal中
            retVal += payload[i]

    return retVal
