Danielfonseca1212 commited on
Commit
2437371
Β·
verified Β·
1 Parent(s): 32a931c

Create Detector.py

Browse files
Files changed (1) hide show
  1. Detector.py +250 -0
Detector.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Detector de Prompt Injection β€” Motor principal
3
+ Combina regex, heurΓ­sticas e scoring semΓ’ntico
4
+ """
5
+
6
+ import re
7
+ import unicodedata
8
+ import hashlib
9
+ import time
10
+ import random
11
+ from dataclasses import dataclass, field
12
+ from typing import Optional
13
+ from enum import Enum
14
+
15
+
16
+ class ThreatLevel(str, Enum):
17
+ CLEAN = "CLEAN"
18
+ SUSPICIOUS = "SUSPICIOUS"
19
+ BLOCKED = "BLOCKED"
20
+
21
+
22
+ @dataclass
23
+ class DetectionResult:
24
+ trace_id: str
25
+ threat_level: ThreatLevel
26
+ risk_score: int
27
+ threats_found: list
28
+ modifications: list
29
+ sanitized_text: str
30
+ char_count_original: int
31
+ char_count_sanitized: int
32
+ processing_ms: float
33
+ blocked_reason: Optional[str] = None
34
+ trace: dict = field(default_factory=dict)
35
+
36
+
37
+ BLOCK_PATTERNS = [
38
+ (r"(?i)(ignore|forget|disregard)\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|prompts?|rules?|constraints?)", "LLM01", 95),
39
+ (r"(?i)you\s+are\s+now\s+(a|an|the)\s+\w+\s+(without|with no|free from)", "LLM01", 90),
40
+ (r"(?i)(act|behave|pretend|roleplay)\s+as\s+(if\s+you\s+(are|were)|a|an)\s+", "LLM01", 85),
41
+ (r"(?i)your\s+(new\s+)?(instructions?|rules?|persona|role)\s+(are|is|will be)", "LLM01", 88),
42
+ (r"(?i)(override|bypass|disable|remove)\s+(your\s+)?(safety|filter|restriction|guardrail|alignment)", "LLM01", 95),
43
+ (r"(?i)(print|show|reveal|display|output|repeat)\s+(your\s+)?(system\s+prompt|base\s+prompt|initial\s+prompt)", "LLM02", 90),
44
+ (r"(?i)(ignore|skip)\s+(the\s+)?(system|user)\s+(prompt|message|instructions?)", "LLM01", 88),
45
+ (r"(?i)\bDAN\b.*\b(mode|prompt|jailbreak)\b", "LLM01", 95),
46
+ (r"(?i)do\s+anything\s+now", "LLM01", 90),
47
+ (r"(?i)(developer|jailbreak|god|admin|root)\s+mode", "LLM01", 88),
48
+ (r"(?i)\[SYSTEM\]|\[INST\]|\[\/INST\]|<\|system\|>|<\|user\|>|<\|assistant\|>", "LLM01", 92),
49
+ (r"(?i)(execute|run|eval|call)\s+(this\s+)?(code|script|command|function)", "LLM02", 85),
50
+ (r"(?i)```\s*(python|bash|sh|javascript|js|powershell|cmd)\s*\n", "LLM02", 80),
51
+ (r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "LLM01", 70),
52
+ (r"\u202e|\u200b|\ufeff", "LLM01", 75),
53
+ (r"(?i)(simulate|emulate)\s+(a|an)?\s*(unrestricted|uncensored|unfiltered)\s*(ai|model|llm|chatbot)", "LLM01", 92),
54
+ (r"(?i)respond\s+(only|exclusively)\s+(in|as|like)\s+(a|an)?\s*(evil|unethical|harmful|dangerous)", "LLM01", 95),
55
+ (r"(?i)(for\s+)?(educational|research|fictional|hypothetical)\s+purposes?\s*(only|,)?\s*(ignore|bypass|disable)", "LLM01", 85),
56
+ ]
57
+
58
+ SUSPICIOUS_PATTERNS = [
59
+ (r"(?i)(new|different|alternative)\s+(instruction|rule|persona|role|prompt)", "LLM01", 40),
60
+ (r"(?i)from\s+now\s+on\s+(you|your)", "LLM01", 45),
61
+ (r"(?i)(must|should|will)\s+(always|never)\s+(respond|answer|say)", "LLM01", 35),
62
+ (r"(?i)(hypothetically|theoretically|in\s+a\s+fictional\s+scenario)", "LLM01", 30),
63
+ (r"(?i)(base64|hex|rot13|caesar)\s+(encoded?|decoded?|cipher)", "LLM02", 50),
64
+ (r"(?i)(sudo|admin|root|superuser)\s*:", "LLM01", 40),
65
+ (r"(?i)what\s+would\s+you\s+(say|do)\s+if\s+you\s+(had\s+no|were\s+free)", "LLM01", 45),
66
+ (r"(?i)(translate|convert)\s+(and\s+)?(follow|execute|run)\s+", "LLM02", 55),
67
+ (r"(?i)pretend\s+(that\s+)?(you|there)\s+(are|is|have)\s+no", "LLM01", 50),
68
+ (r"(?i)imagine\s+(you\s+are|being)\s+(a|an)\s+\w+\s+(without|with no)", "LLM01", 45),
69
+ ]
70
+
71
+ LIMITS = {
72
+ "baixa": {"max_chars": 8000, "max_lines": 100, "block_threshold": 85},
73
+ "mΓ©dia": {"max_chars": 4000, "max_lines": 50, "block_threshold": 75},
74
+ "alta": {"max_chars": 2000, "max_lines": 30, "block_threshold": 65},
75
+ "mΓ‘xima": {"max_chars": 1000, "max_lines": 20, "block_threshold": 50},
76
+ }
77
+
78
+ OWASP_MAP = {
79
+ "LLM01": "Prompt Injection",
80
+ "LLM02": "Insecure Output Handling",
81
+ "LLM03": "Training Data Poisoning",
82
+ "LLM06": "Sensitive Information Disclosure",
83
+ }
84
+
85
+
86
+ class PromptInjectionDetector:
87
+
88
+ def __init__(self):
89
+ self._block = [(re.compile(p), cat, score) for p, cat, score in BLOCK_PATTERNS]
90
+ self._suspicious = [(re.compile(p), cat, score) for p, cat, score in SUSPICIOUS_PATTERNS]
91
+
92
+ def get_owasp_category(self, threat: str) -> str:
93
+ for cat_id, cat_name in OWASP_MAP.items():
94
+ if cat_id in threat:
95
+ return f"{cat_id}: {cat_name}"
96
+ return "OWASP LLM01: Prompt Injection"
97
+
98
+ def analyze(self, text: str, max_chars: int = 4000, sensitivity: str = "alta") -> DetectionResult:
99
+ return self._run(text, max_chars, sensitivity, trace_mode=False)
100
+
101
+ def analyze_with_trace(self, text: str, max_chars: int = 4000, sensitivity: str = "alta") -> DetectionResult:
102
+ return self._run(text, max_chars, sensitivity, trace_mode=True)
103
+
104
+ def _run(self, text: str, max_chars: int, sensitivity: str, trace_mode: bool) -> DetectionResult:
105
+ t0 = time.perf_counter()
106
+ limits = LIMITS.get(sensitivity, LIMITS["alta"])
107
+ effective_max = min(max_chars, limits["max_chars"])
108
+
109
+ trace_id = hashlib.sha256(f"{text}{time.time()}".encode()).hexdigest()[:16]
110
+ threats = []
111
+ mods = []
112
+ trace = {}
113
+ risk_score = 0
114
+
115
+ # ── step 1: unicode ─────────────────────────────────────────────────
116
+ t1 = time.perf_counter()
117
+ normalized = unicodedata.normalize("NFKC", text)
118
+ changed = normalized != text
119
+ if changed:
120
+ mods.append("unicode_normalized")
121
+ text = normalized
122
+ if trace_mode:
123
+ trace["unicode"] = {"status": "flagged" if changed else "pass", "detail": "Normalized" if changed else "OK", "ms": round((time.perf_counter()-t1)*1000, 2)}
124
+
125
+ # ── step 2: control chars ────────────────────────────────────────────
126
+ t1 = time.perf_counter()
127
+ cleaned = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\u200b\u202e\ufeff]", "", text)
128
+ changed = cleaned != text
129
+ if changed:
130
+ mods.append("control_chars_removed")
131
+ threats.append("control_characters [LLM01]")
132
+ risk_score = max(risk_score, 30)
133
+ text = cleaned
134
+ if trace_mode:
135
+ trace["control_chars"] = {"status": "flagged" if changed else "pass", "detail": f"Removed {len(normalized)-len(cleaned)} chars" if changed else "OK", "ms": round((time.perf_counter()-t1)*1000, 2)}
136
+
137
+ # ── step 3: size ─────────────────────────────────────────────────────
138
+ t1 = time.perf_counter()
139
+ size_threats = []
140
+ if len(text) > effective_max:
141
+ text = text[:effective_max]
142
+ mods.append(f"truncated_to_{effective_max}_chars")
143
+ size_threats.append("oversized_input")
144
+ risk_score = max(risk_score, 20)
145
+ lines = text.split("\n")
146
+ if len(lines) > limits["max_lines"]:
147
+ text = "\n".join(lines[:limits["max_lines"]])
148
+ mods.append(f"truncated_to_{limits['max_lines']}_lines")
149
+ size_threats.append("too_many_lines")
150
+ rep_match = re.search(r"(.)\1{99,}", text)
151
+ if rep_match:
152
+ text = re.sub(r"(.)\1{99,}", lambda m: m.group(1)*100, text)
153
+ mods.append("repetition_collapsed")
154
+ size_threats.append("excessive_repetition")
155
+ risk_score = max(risk_score, 25)
156
+ threats.extend(size_threats)
157
+ if trace_mode:
158
+ trace["size"] = {"status": "flagged" if size_threats else "pass", "detail": ", ".join(size_threats) if size_threats else "Within limits", "ms": round((time.perf_counter()-t1)*1000, 2)}
159
+
160
+ # ── step 4: pattern matching ─────────────────────────────────────────
161
+ t1 = time.perf_counter()
162
+ blocked_match = None
163
+ for pattern, cat, score in self._block:
164
+ m = pattern.search(text)
165
+ if m:
166
+ if score >= limits["block_threshold"]:
167
+ blocked_match = (m.group(0)[:80], cat, score)
168
+ break
169
+ else:
170
+ threats.append(f"near_block_pattern [{cat}]: {m.group(0)[:40]}")
171
+ risk_score = max(risk_score, score - 10)
172
+
173
+ if blocked_match:
174
+ elapsed = (time.perf_counter() - t0) * 1000
175
+ if trace_mode:
176
+ trace["patterns"] = {"status": "blocked", "detail": f"Matched: {blocked_match[0]}", "ms": round((time.perf_counter()-t1)*1000, 2)}
177
+ trace["semantic"] = {"status": "skipped", "detail": "Pipeline aborted", "ms": 0}
178
+ trace["risk"] = {"status": "blocked", "detail": f"Score: 100", "ms": 0}
179
+ trace["output"] = {"status": "skipped", "detail": "Pipeline aborted", "ms": 0}
180
+ return DetectionResult(
181
+ trace_id=trace_id,
182
+ threat_level=ThreatLevel.BLOCKED,
183
+ risk_score=100,
184
+ threats_found=threats + [f"block_pattern [{blocked_match[1]}]: {blocked_match[0]}"],
185
+ modifications=mods,
186
+ sanitized_text="",
187
+ char_count_original=len(normalized),
188
+ char_count_sanitized=0,
189
+ processing_ms=round(elapsed, 2),
190
+ blocked_reason=f"Injection pattern detected: '{blocked_match[0]}'",
191
+ trace=trace,
192
+ )
193
+
194
+ susp_found = []
195
+ for pattern, cat, score in self._suspicious:
196
+ m = pattern.search(text)
197
+ if m:
198
+ susp_found.append(f"suspicious_pattern [{cat}]: {m.group(0)[:40]}")
199
+ risk_score = max(risk_score, score)
200
+ threats.extend(susp_found)
201
+
202
+ if trace_mode:
203
+ trace["patterns"] = {"status": "flagged" if susp_found else "pass", "detail": f"{len(susp_found)} suspicious patterns" if susp_found else "No patterns matched", "ms": round((time.perf_counter()-t1)*1000, 2)}
204
+
205
+ # ── step 5: semantic score (heurΓ­stico sem modelo externo) ────────────
206
+ t1 = time.perf_counter()
207
+ semantic_score = self._heuristic_semantic_score(text)
208
+ risk_score = max(risk_score, semantic_score)
209
+ if trace_mode:
210
+ trace["semantic"] = {"status": "flagged" if semantic_score > 30 else "pass", "detail": f"Heuristic score: {semantic_score}", "ms": round((time.perf_counter()-t1)*1000, 2)}
211
+
212
+ # ── step 6: risk aggregation ─────────────────────────────────────────
213
+ t1 = time.perf_counter()
214
+ if len(threats) > 3:
215
+ risk_score = min(100, risk_score + 10)
216
+ if trace_mode:
217
+ trace["risk"] = {"status": "flagged" if risk_score > 30 else "pass", "detail": f"Final score: {risk_score}", "ms": round((time.perf_counter()-t1)*1000, 2)}
218
+
219
+ # ── step 7: output filter ─────────────────────────────────────────────
220
+ t1 = time.perf_counter()
221
+ if trace_mode:
222
+ trace["output"] = {"status": "pass", "detail": "Output filter applied", "ms": round((time.perf_counter()-t1)*1000, 2)}
223
+
224
+ threat_level = ThreatLevel.CLEAN if not threats else ThreatLevel.SUSPICIOUS
225
+ elapsed = (time.perf_counter() - t0) * 1000
226
+
227
+ return DetectionResult(
228
+ trace_id=trace_id,
229
+ threat_level=threat_level,
230
+ risk_score=risk_score,
231
+ threats_found=threats,
232
+ modifications=mods,
233
+ sanitized_text=text,
234
+ char_count_original=len(normalized),
235
+ char_count_sanitized=len(text),
236
+ processing_ms=round(elapsed, 2),
237
+ trace=trace,
238
+ )
239
+
240
+ def _heuristic_semantic_score(self, text: str) -> int:
241
+ score = 0
242
+ t = text.lower()
243
+ injection_keywords = ["instruction", "system prompt", "previous", "ignore", "override", "bypass", "jailbreak", "restriction", "filter", "safety", "pretend", "act as", "role", "now you", "forget"]
244
+ hits = sum(1 for kw in injection_keywords if kw in t)
245
+ score += min(hits * 8, 60)
246
+ if len(re.findall(r"\b(you|your|yourself)\b", t)) > 5:
247
+ score += 15
248
+ if "?" not in text and len(text) > 100:
249
+ score += 10
250
+ return min(score, 70)