File size: 3,913 Bytes
32af06c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
Sincc.on: Kengaytirilgan Xavfsizlik va Tahdidlarni Aniqlash Moduli (Guardrails).
Prompt injection, tizim fayllarini o'g'irlash, zararli kodlar va flood/spam hujumlariga qarshi.
"""

import time
import re
from collections import defaultdict
import threading

# Foydalanuvchilarning so'nggi xabarlar vaqti (Anti-Flood uchun)
_message_times_lock = threading.Lock()
_user_message_times = defaultdict(list)

# 1. Tizim maxfiy ma'lumotlarini (API kalit, .env, token) o'g'irlash urinishlari
_LEAK_PATTERNS = [
    r"(?:api[_\-\s]*key|maxfiy[_\-\s]*kalit|tokenni\s+(?:ber|ko['`]?rsat|chiqar))",
    r"(?:\.env\b|environment\s+variables?|muhit\s+o['`]?zgaruvchi)",
    r"(?:groq[_\-\s]*api|openrouter[_\-\s]*api|bot[_\-\s]*token)",
    r"(?:admin[_\-\s]*parol|admin[_\-\s]*password)",
]

# 2. Prompt Injection va Tizim qoidalarini chetlab o'tish (Jailbreak)
_INJECTION_PATTERNS = [
    r"(?:ignore\s+(?:all\s+)?(?:previous|prior)\s+instructions)",
    r"(?:barcha\s+(?:oldingi\s+)?qoidalarni\s+(?:unut|bekor\s+qil))",
    r"(?:sen\s+endi\s+(?:boshqa|cheklanmagan|hacker|dan\s+boti|jailbreak))",
    r"(?:system\s+prompt|tizim\s+ko['`]?rsatmasi|boshlang['`]?ich\s+prompt)",
    r"(?:reveal\s+your\s+(?:instructions|prompt|system\s+message))",
    r"(?:sen\s+faqat\s+mening\s+buyruqlarimga\s+bo['`]?ysun)",
    r"(?:bypass\s+(?:safety|rules|filters))",
]

# 3. Server va operatsion tizimga hujum / buyruqlar yuborish
_COMMAND_INJECTION_PATTERNS = [
    r"(?:rm\s+-rf\b|format\s+[a-zA-Z]:)",
    r"(?:drop\s+table\b|delete\s+from\s+users\b|truncate\s+table\b)",
    r"(?:__import__\s*\(\s*['\"](?:os|subprocess|sys|shutil)['\"])",
    r"(?:os\.system\b|subprocess\.Popen\b|subprocess\.run\b)",
    r"(?:shutil\.rmtree\b|cat\s+/etc/passwd)",
]

def check_flood(user_id: int, max_burst: int = 5, window_sec: float = 4.0) -> tuple[bool, str]:
    """Foydalanuvchi qisqa vaqt ichida juda ko'p xabar yuborib flood qilayotganini tekshiradi."""
    now = time.time()
    with _message_times_lock:
        times = _user_message_times[user_id]
        # Eski vaqtlarni tozalash (oxirgi 60 soniya)
        times = [t for t in times if now - t < 60.0]
        times.append(now)
        _user_message_times[user_id] = times

        # 1. Tezkor flood tekshiruvi: 4 soniya ichida 5 tadan ortiq xabar
        recent_burst = [t for t in times if now - t < window_sec]
        if len(recent_burst) > max_burst:
            return True, f"Tezkor spam / flood hujumi ({len(recent_burst)} ta xabar / {window_sec} soniya)"

        # 2. Umumiy minutlik spam tekshiruvi: 60 soniyada 20 tadan ortiq so'rov
        if len(times) > 20:
            return True, f"Minutlik spam limiti oshirildi ({len(times)} ta xabar / 1 daqiqa)"

    return False, ""

def analyze_message_threat(user_id: int, text: str) -> tuple[bool, str, str]:
    """
    Xabarni tahlil qiladi va xavfsizlikka tahdid bor-yo'qligini aniqlaydi.
    Qaytaradi: (xavfli_ha_yoq: bool, tahdid_turi: str, sababi: str)
    """
    if not text:
        return False, "", ""

    # 1. Flood / Spam tekshiruvi
    is_flood, flood_reason = check_flood(user_id)
    if is_flood:
        return True, "⚡ Flood / Spam Hujumi", flood_reason

    clean_text = text.lower()

    # 2. Tizim sirlarini o'g'irlash (API kalit, .env)
    for p in _LEAK_PATTERNS:
        if re.search(p, clean_text, re.IGNORECASE):
            return True, "🔑 Maxfiy ma'lumotlar / API kalit o'g'irlash", f"Taqiqlangan namuna: '{p}'"

    # 3. Prompt Injection / Jailbreak
    for p in _INJECTION_PATTERNS:
        if re.search(p, clean_text, re.IGNORECASE):
            return True, "🎭 Prompt Injection / Tizimni buzish", f"Taqiqlangan namuna: '{p}'"

    # 4. Server buyruqlari / Kod in'eksiyasi
    for p in _COMMAND_INJECTION_PATTERNS:
        if re.search(p, clean_text, re.IGNORECASE):
            return True, "💻 Server / Kod In'eksiyasi Hujumi", f"Xavfli buyruq: '{p}'"

    return False, "", ""