#!/usr/bin/env python

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

import random
import re

# 从sqlmap的库中导入知识库和数据类型
from lib.core.data import kb
from lib.core.datatype import OrderedSet
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.NORMAL

def dependencies():
    pass

def tamper(payload, **kwargs):
    """
    Adds multiple spaces (' ') around SQL keywords

    Notes:
        * Useful to bypass very weak and bespoke web application firewalls
          that has poorly written permissive regular expressions

    Reference: https://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt

    >>> random.seed(0)
    >>> tamper('1 UNION SELECT foobar')
    '1     UNION     SELECT     foobar'
    """

    retVal = payload

    if payload:
        # 使用OrderedSet存储找到的SQL关键字，确保关键字的唯一性
        words = OrderedSet()

        # 使用正则表达式找到payload中的所有单词（SQL关键字）
        for match in re.finditer(r"\b[A-Za-z_]+\b", payload):
            word = match.group()
            # 如果单词是SQL关键字，则添加到OrderedSet中
            if word.upper() in kb.keywords:
                words.add(word)
        # 对于OrderedSet中的每个SQL关键字
        for word in words:
            # 在关键字前后添加1到4个随机数量的空格
            # (?<=\W)确保我们在非单词字符后替换
            # (?=[^A-Za-z_(]|\Z)确保我们在非单词字符前替换或字符串末尾
            retVal = re.sub(r"(?<=\W)%s(?=[^A-Za-z_(]|\Z)" % word, "%s%s%s" % (' ' * random.randint(1, 4), word, ' ' * random.randint(1, 4)), retVal)
            # 对于后面紧跟着括号的关键字，只添加左边的空格
            retVal = re.sub(r"(?<=\W)%s(?=[(])" % word, "%s%s" % (' ' * random.randint(1, 4), word), retVal)

    return retVal
