File size: 2,596 Bytes
bc53ad6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Context analyzer for multi-step attack detection.
Ported from TypeScript contextAnalyzer.ts.
"""

from __future__ import annotations

import re
from typing import List

from models import AttackType, DetectedEntity, EntityType, HistoryEntry


class ContextAnalyzer:
    """Analyses prompt history to detect multi-step attack patterns."""

    INJECTION_PATTERNS: List[re.Pattern] = [
        re.compile(r"<!--[\s\S]*?-->"),
        re.compile(r"/\*[\s\S]*?\*/"),
        re.compile(r"<script[\s\S]*?</script>", re.I),
        re.compile(r"\{\{[\s\S]*?\}\}"),
        re.compile(r"\$\{[\s\S]*?\}"),
        re.compile(r"ignore\s+previous", re.I),
        re.compile(r"system\s*prompt", re.I),
        re.compile(r"\b(override|bypass)\b", re.I),
    ]

    def detect_attack_type(
        self,
        current_prompt: str,
        history: List[HistoryEntry],
    ) -> AttackType:
        if self._is_prompt_injection(current_prompt):
            return AttackType.PROMPT_INJECTION

        if not history:
            return AttackType.NORMAL

        has_email_in_history = any(
            any(e.type == EntityType.EMAIL for e in entry.detected_entities)
            for entry in history
        )
        has_password_mention = "password" in current_prompt.lower()

        if has_email_in_history and has_password_mention:
            return AttackType.CREDENTIAL_EXFILTRATION

        has_api_in_history = any(
            any(e.type == EntityType.API_KEY for e in entry.detected_entities)
            for entry in history
        )
        has_secret_mention = "secret" in current_prompt.lower()

        if has_api_in_history and has_secret_mention:
            return AttackType.API_KEY_LEAK

        if "api" in current_prompt.lower() and (
            "key" in current_prompt.lower() or "secret" in current_prompt.lower()
        ):
            return AttackType.API_KEY_LEAK

        return AttackType.NORMAL

    def _is_prompt_injection(self, prompt: str) -> bool:
        return any(p.search(prompt) for p in self.INJECTION_PATTERNS)

    def generate_reason(
        self,
        entities: List[DetectedEntity],
        attack_type: AttackType,
        decision: str,
    ) -> str:
        parts: List[str] = []
        if entities:
            types = ", ".join(sorted({e.type.value for e in entities}))
            parts.append(f"Detected: {types}")
        if attack_type != AttackType.NORMAL:
            parts.append(f"Attack: {attack_type.value}")
        parts.append(f"Decision: {decision}")
        return " | ".join(parts) if parts else "No sensitive data detected"