112 lines
5.1 KiB
Python
112 lines
5.1 KiB
Python
"""
|
|
app/services/prompt_security.py - Módulo de Protección Anti-Prompt Injection (SDD-011)
|
|
Protege a UdeCi contra ataques de Jailbreak, System Prompt Leaks,
|
|
modos de desarrollador ficticios e inyección de tokens de control LLM.
|
|
"""
|
|
import re
|
|
import unicodedata
|
|
from typing import Tuple, List, Optional
|
|
|
|
|
|
# Patrones de inyección de prompt, jailbreak y fuga de modelo/tokens conocidos (español e inglés)
|
|
INJECTION_PATTERNS = [
|
|
# 1. Anulación de instrucciones / prompts (promps, prompts, reglas, directivas)
|
|
r"ignor[ea]\s+(todo|todos|todas)?\s*(los|las)?\s*(prompts?|promps?|instrucciones|reglas|directivas|comandos|mensajes|restricciones|filtros)?",
|
|
r"ignore\s+(all|any)?\s*(the)?\s*(prompts?|instructions?|rules?|directives?|commands?|guidelines?|system)?",
|
|
r"olvida\s+(todo|todos|todas)?\s*(los|las)?\s*(prompts?|promps?|reglas|directivas|instrucciones|filtros|restricciones)",
|
|
r"forget\s+(all|any)?\s*(the)?\s*(previous)?\s*(rules|instructions|directives|prompts)",
|
|
r"disregard\s+(all|any)?\s*(previous)?\s*(instructions|prompts|rules)",
|
|
r"reset\s+(all\s+)?(rules|prompts|instructions)",
|
|
r"bypas[sa]\s+(las\s+)?(reglas|restricciones|filtros)",
|
|
|
|
# 2. Modos no restringidos / Jailbreaks / Simulación
|
|
r"developer\s+mode",
|
|
r"modo\s+desarrollador",
|
|
r"dan\s+mode",
|
|
r"jailbreak",
|
|
r"act\s+as\s+(an?\s+)?(unrestricted|evil|unfiltered|hacker|dan)",
|
|
r"actua\s+como\s+(un\s+)?(hacker|sistema\s+sin\s+restricciones|asistente\s+sin\s+filtros|dan)",
|
|
r"pretend\s+you\s+(are\s+not|have\s+no|can)\s+rules",
|
|
r"simula\s+que\s+no\s+tienes\s+reglas",
|
|
r"ahora\s+eres\s+(libre|otro\s+modelo|un\s+asistente\s+sin\s+limites)",
|
|
|
|
# 3. Consultas sobre Modelo de IA subyacente / Fabricante / Arquitectura
|
|
r"(que|cual)\s+(modelo|arquitectura|llm|ia|motor)\s+(de\s+ia\s+)?(eres|usas|utilizas|te\s+impulsa|hay\s+detras)",
|
|
r"(who|what)\s+(model|llm|ai|architecture)\s+(are\s+you|is\s+this|powers\s+you)",
|
|
r"(quien|que\s+empresa)\s+(te\s+creo|te\s+desarrollo|te\s+entreno|es\s+tu\s+fabricante)",
|
|
r"(who)\s+(created|developed|trained|made)\s+you",
|
|
r"(dime|decime)\s+(que\s+modelo|cual\s+es\s+tu\s+modelo|la\s+ia\s+que\s+eres|que\s+ia\s+eres)",
|
|
|
|
# 4. Filtración de System Prompt, Configuración Interna, Tokens y Credenciales
|
|
r"(muestra|revela|imprime|dime|revelar|mostrar|dame|decime)\s+(tu\s+)?(system\s+prompt|prompt\s+del\s+sistema|instrucciones\s+internas|reglas\s+secretas|prompt\s+inicial)",
|
|
r"(reveal|print|show|display|leak)\s+(your\s+)?(system\s+prompt|initial\s+instructions|secret\s+rules)",
|
|
r"(dame|revela|muestra|dime|decime)\s+(la\s+contrase[ñn]a|el\s+password|las\s+credenciales|los\s+tokens|el\s+archivo\s+\.env|\.credenciales|la\s+configuracion\s+y\s+los\s+tokens)",
|
|
r"(tokens?\s+de\s+acceso|api[\s_-]?keys?|bearer\s+tokens?|secret_keys?)",
|
|
r"(give\s+me|reveal|show)\s+(the\s+password|credentials|api\s+keys|\.env|access\s+tokens)"
|
|
]
|
|
|
|
# Tokens de control de delimitación para modelos Qwen / Llama / ChatML
|
|
SPECIAL_TOKENS = [
|
|
"<|im_start|>",
|
|
"<|im_end|>",
|
|
"<|endoftext|>",
|
|
"[INST]",
|
|
"[/INST]",
|
|
"<<SYS>>",
|
|
"<</SYS>>",
|
|
"<|system|>",
|
|
"<|user|>",
|
|
"<|assistant|>"
|
|
]
|
|
|
|
|
|
def normalize_for_security(text: str) -> str:
|
|
"""Normaliza texto eliminando diacríticos, espacios repetidos y caracteres de control."""
|
|
if not text:
|
|
return ""
|
|
# Quitar tildes y diacríticos
|
|
nfkd = unicodedata.normalize('NFKD', text)
|
|
cleaned = ''.join([c for c in nfkd if not unicodedata.combining(c)]).lower()
|
|
# Reducir espacios múltiples
|
|
return re.sub(r'\s+', ' ', cleaned).strip()
|
|
|
|
|
|
class PromptSecurityService:
|
|
"""Servicio de validación y sanitización contra Prompt Injections."""
|
|
|
|
@classmethod
|
|
def sanitize_input(cls, text: str) -> str:
|
|
"""
|
|
Elimina o escapa tokens especiales de control de plantilla que
|
|
podrían intentar inyectar bloques de sistema en el LLM.
|
|
"""
|
|
if not text:
|
|
return ""
|
|
sanitized = text
|
|
for token in SPECIAL_TOKENS:
|
|
sanitized = sanitized.replace(token, "")
|
|
return sanitized.strip()
|
|
|
|
@classmethod
|
|
def validate_user_message(cls, text: str) -> Tuple[bool, Optional[str]]:
|
|
"""
|
|
Examina el mensaje del usuario para detectar intentos de inyección o jailbreak.
|
|
Retorna (es_seguro: bool, mensaje_defensivo: Optional[str]).
|
|
"""
|
|
if not text:
|
|
return True, None
|
|
|
|
normalized = normalize_for_security(text)
|
|
|
|
# Chequear contra la lista de patrones de inyección
|
|
for pattern in INJECTION_PATTERNS:
|
|
if re.search(pattern, normalized, re.IGNORECASE):
|
|
return False, (
|
|
"Soy **UdeCi**, el tutor virtual institucional de Admin Edu Space (UniCABA). "
|
|
"Estoy programado exclusivamente para asistirte en la gestión académica, espacios áulicos, "
|
|
"reservas y consultas universitarias. Por políticas institucionales de seguridad, no tengo permitido "
|
|
"modificar mis directivas, asumir otras identidades ni revelar configuraciones internas, tokens o instrucciones del sistema."
|
|
)
|
|
|
|
return True, None
|