Download webapp/security_engine.py from TeknikoAI/specialist-security-models: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/TeknikoAI/specialist-security-models/resolve/main/webapp/security_engine.py
- Command line
-
hf download hf://TeknikoAI/specialist-security-models/webapp/security_engine.py
-
curl -L -o security_engine.py https://huggingface.co/TeknikoAI/specialist-security-models/resolve/main/webapp/security_engine.py
19.2 kB
| """ | |
| AegisVault Security Engine | |
| Loads and runs all 8 quantized INT8 ONNX MiniLM security specialist models | |
| from the workspace for real-time system protection. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import re | |
| import time | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import onnxruntime as ort | |
| from transformers import AutoTokenizer | |
| MODEL_DIRS = [ | |
| "sec_auth_anomaly_gate", | |
| "sec_prompt_injection_gate", | |
| "sec_domain_router", | |
| "sec_incident_action", | |
| "sec_risk_severity", | |
| "sec_alert_indicators", | |
| "sec_ioc_extract", | |
| "sec_log_redact_secrets", | |
| ] | |
| MODEL_DESCRIPTIONS = { | |
| "sec_auth_anomaly_gate": "Detects credential stuffing, impossible travel, brute-force, and anomalous logins.", | |
| "sec_prompt_injection_gate": "Blocks prompt injection, jailbreaks, and system-prompt extraction attempts.", | |
| "sec_domain_router": "Routes telemetry across Benign, App/Identity, Network Traffic, and Host System domains.", | |
| "sec_incident_action": "Recommends automated containment: Allow, Investigate, Revoke Credentials, or Isolate.", | |
| "sec_risk_severity": "Scores security event risk severity on a calibrated 1 (Low) to 5 (Critical) scale.", | |
| "sec_alert_indicators": "Multi-label detector for credential risk, data exfiltration, defense evasion, and lateral movement.", | |
| "sec_ioc_extract": "Extracts Indicators of Compromise (IP addresses, domains, and user accounts) from logs.", | |
| "sec_log_redact_secrets": "Detects and redacts leaked API keys, passwords, and bearer tokens before log storage.", | |
| } | |
| def _softmax(x: np.ndarray) -> np.ndarray: | |
| x = x - np.max(x, axis=-1, keepdims=True) | |
| e = np.exp(x) | |
| return e / np.sum(e, axis=-1, keepdims=True) | |
| def _sigmoid(x: np.ndarray) -> np.ndarray: | |
| return 1.0 / (1.0 + np.exp(-np.clip(x, -40.0, 40.0))) | |
| class SpecialistModel: | |
| def __init__(self, model_dir: Path, tokenizer: Any) -> None: | |
| self.model_dir = model_dir | |
| self.meta_path = model_dir / "meta.json" | |
| self.onnx_path = model_dir / "specialist_int8.onnx" | |
| self.tokenizer = tokenizer | |
| with open(self.meta_path, "r", encoding="utf-8") as f: | |
| self.meta = json.load(f) | |
| self.name: str = self.meta["name"] | |
| self.primitive: str = self.meta["primitive"] | |
| self.labels: list[str] = self.meta["labels"] | |
| self.temperature: float = float(self.meta.get("temperature") or 1.0) | |
| self.thresholds: list[float] | None = self.meta.get("thresholds") | |
| self.description: str = MODEL_DESCRIPTIONS.get(self.name, "") | |
| sess_opts = ort.SessionOptions() | |
| sess_opts.intra_op_num_threads = max(1, min(4, os.cpu_count() or 2)) | |
| sess_opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL | |
| self.session = ort.InferenceSession( | |
| str(self.onnx_path), | |
| sess_options=sess_opts, | |
| providers=["CPUExecutionProvider"], | |
| ) | |
| def predict(self, text: str) -> dict[str, Any]: | |
| t0 = time.perf_counter() | |
| if self.primitive == "extract": | |
| result = self._predict_extract(text) | |
| else: | |
| result = self._predict_sequence(text) | |
| result["latency_ms"] = round((time.perf_counter() - t0) * 1000.0, 2) | |
| result["model"] = self.name | |
| result["primitive"] = self.primitive | |
| return result | |
| def _predict_sequence(self, text: str) -> dict[str, Any]: | |
| enc = self.tokenizer( | |
| text, | |
| truncation=True, | |
| max_length=256, | |
| return_tensors="np", | |
| ) | |
| inputs = { | |
| "input_ids": enc["input_ids"].astype(np.int64), | |
| "attention_mask": enc["attention_mask"].astype(np.int64), | |
| } | |
| logits = self.session.run(None, inputs)[0][0] | |
| scaled = logits / max(self.temperature, 1e-5) | |
| if self.primitive == "tags": | |
| probs = _sigmoid(scaled) | |
| thresholds = self.thresholds or [0.5] * len(self.labels) | |
| scores = {lbl: round(float(p), 4) for lbl, p in zip(self.labels, probs)} | |
| active = [ | |
| lbl | |
| for lbl, p, th in zip(self.labels, probs, thresholds) | |
| if float(p) >= float(th) | |
| ] | |
| return { | |
| "active_tags": active, | |
| "scores": scores, | |
| "thresholds": dict(zip(self.labels, thresholds)), | |
| } | |
| probs = _softmax(scaled) | |
| best_idx = int(np.argmax(probs)) | |
| scores = {lbl: round(float(p), 4) for lbl, p in zip(self.labels, probs)} | |
| out: dict[str, Any] = { | |
| "label": self.labels[best_idx], | |
| "confidence": round(float(probs[best_idx]), 4), | |
| "scores": scores, | |
| } | |
| if self.primitive == "noul": | |
| out["flagged"] = self.labels[best_idx] == "TRUE" | |
| out["risk_prob"] = round(float(probs[self.labels.index("TRUE")]), 4) | |
| elif self.primitive == "score": | |
| numeric_vals = np.array([float(lbl) for lbl in self.labels], dtype=np.float64) | |
| expected = float(np.sum(probs * numeric_vals)) | |
| out["severity_level"] = int(self.labels[best_idx]) | |
| out["expected_score"] = round(expected, 2) | |
| return out | |
| def _predict_extract(self, text: str) -> dict[str, Any]: | |
| enc = self.tokenizer( | |
| text, | |
| truncation=True, | |
| max_length=256, | |
| return_offsets_mapping=True, | |
| return_tensors="np", | |
| ) | |
| offsets = enc["offset_mapping"][0] | |
| inputs = { | |
| "input_ids": enc["input_ids"].astype(np.int64), | |
| "attention_mask": enc["attention_mask"].astype(np.int64), | |
| } | |
| logits = self.session.run(None, inputs)[0][0] # [seq, num_labels] | |
| probs = _softmax(logits / max(self.temperature, 1e-5)) | |
| pred_ids = np.argmax(probs, axis=-1) | |
| spans: list[dict[str, Any]] = [] | |
| current: dict[str, Any] | None = None | |
| for idx, (pred_id, (start, end)) in enumerate(zip(pred_ids, offsets)): | |
| start_i, end_i = int(start), int(end) | |
| if start_i == 0 and end_i == 0: | |
| if current is not None: | |
| spans.append(current) | |
| current = None | |
| continue | |
| tag = self.labels[int(pred_id)] | |
| conf = float(probs[idx, int(pred_id)]) | |
| if tag == "O": | |
| if current is not None: | |
| spans.append(current) | |
| current = None | |
| continue | |
| prefix, entity_type = tag.split("-", 1) | |
| if prefix == "B": | |
| if current is not None: | |
| spans.append(current) | |
| current = { | |
| "type": entity_type, | |
| "start": start_i, | |
| "end": end_i, | |
| "confs": [conf], | |
| } | |
| elif prefix == "I": | |
| if current is not None and current["type"] == entity_type: | |
| current["end"] = end_i | |
| current["confs"].append(conf) | |
| else: | |
| if current is not None: | |
| spans.append(current) | |
| current = { | |
| "type": entity_type, | |
| "start": start_i, | |
| "end": end_i, | |
| "confs": [conf], | |
| } | |
| if current is not None: | |
| spans.append(current) | |
| # Merge immediately adjacent spans of the same type (e.g. token splits on '-', '.', '_') | |
| merged: list[dict[str, Any]] = [] | |
| for sp in spans: | |
| if ( | |
| merged | |
| and merged[-1]["type"] == sp["type"] | |
| and sp["start"] <= merged[-1]["end"] + 1 | |
| and text[merged[-1]["end"] : sp["start"]].strip() == "" | |
| and (sp["start"] == merged[-1]["end"] or text[merged[-1]["end"] : sp["start"]] in ("", "-", ".", "_", "/", ":", "=")) | |
| ): | |
| merged[-1]["end"] = sp["end"] | |
| merged[-1]["confs"].extend(sp["confs"]) | |
| else: | |
| merged.append(sp) | |
| final_entities = [] | |
| for sp in merged: | |
| s_i, e_i = sp["start"], sp["end"] | |
| # For secret redaction, expand partial subword hits to full token boundaries | |
| # so prefix/suffix characters of API keys or tokens never leak. | |
| if self.name == "sec_log_redact_secrets": | |
| boundary_chars = set(" \t\r\n,;\"'()[]{}<>=") | |
| while s_i > 0 and text[s_i - 1] not in boundary_chars: | |
| s_i -= 1 | |
| while e_i < len(text) and text[e_i] not in boundary_chars: | |
| e_i += 1 | |
| val = text[s_i:e_i].strip() | |
| if not val or len(val) < 3 or not any(ch.isalnum() for ch in val): | |
| continue | |
| final_entities.append( | |
| { | |
| "type": sp["type"], | |
| "text": val, | |
| "start": s_i, | |
| "end": e_i, | |
| "confidence": round(float(np.mean(sp["confs"])), 4), | |
| "source": "onnx", | |
| } | |
| ) | |
| # Defense-in-depth DLP guardrail for high-entropy key patterns alongside ONNX extraction | |
| if self.name == "sec_log_redact_secrets": | |
| dlp_patterns = [ | |
| ("API_KEY", r"\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{12,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{20,})\b"), | |
| ("TOKEN", r"\b(?:ghp_[A-Za-z0-9]{12,}|xox[baprs]-[A-Za-z0-9-]{10,}|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,})\b"), | |
| ("PASSWORD", r"\b(?:password|passwd|db_password|secret_key|client_secret)\s*[:=]\s*[^\s,;\"']+"), | |
| ] | |
| for etype, pat in dlp_patterns: | |
| for m in re.finditer(pat, text, flags=re.IGNORECASE): | |
| s_i, e_i = m.start(), m.end() | |
| # Replace any narrower overlapping ONNX sub-span with the full secret span | |
| overlapping = [ex for ex in final_entities if not (e_i <= ex["start"] or s_i >= ex["end"])] | |
| if overlapping: | |
| min_s = min(s_i, *(ex["start"] for ex in overlapping)) | |
| max_e = max(e_i, *(ex["end"] for ex in overlapping)) | |
| final_entities = [ex for ex in final_entities if ex not in overlapping] | |
| final_entities.append( | |
| { | |
| "type": etype, | |
| "text": text[min_s:max_e], | |
| "start": min_s, | |
| "end": max_e, | |
| "confidence": 0.99, | |
| "source": "onnx+dlp_guard", | |
| } | |
| ) | |
| else: | |
| final_entities.append( | |
| { | |
| "type": etype, | |
| "text": text[s_i:e_i], | |
| "start": s_i, | |
| "end": e_i, | |
| "confidence": 0.99, | |
| "source": "onnx+dlp_guard", | |
| } | |
| ) | |
| # Deduplicate any remaining overlapping spans by keeping the widest span | |
| final_entities.sort(key=lambda x: (x["start"], -(x["end"] - x["start"]))) | |
| deduped: list[dict[str, Any]] = [] | |
| for ent in final_entities: | |
| if deduped and ent["start"] < deduped[-1]["end"]: | |
| if ent["end"] > deduped[-1]["end"]: | |
| deduped[-1]["end"] = ent["end"] | |
| deduped[-1]["text"] = text[deduped[-1]["start"] : deduped[-1]["end"]] | |
| else: | |
| deduped.append(ent) | |
| final_entities = deduped | |
| redacted_text = text | |
| if self.name == "sec_log_redact_secrets" and final_entities: | |
| chars = list(text) | |
| for ent in sorted(final_entities, key=lambda x: x["start"], reverse=True): | |
| replacement = f"[REDACTED_{ent['type']}]" | |
| chars[ent["start"] : ent["end"]] = list(replacement) | |
| redacted_text = "".join(chars) | |
| return { | |
| "entities": final_entities, | |
| "redacted_text": redacted_text, | |
| "count": len(final_entities), | |
| } | |
| class SecurityEngine: | |
| """Orchestrates all 8 specialist security models for AegisVault.""" | |
| def __init__(self, models_root: Path) -> None: | |
| self.models_root = models_root | |
| self.backbone_id = "sentence-transformers/all-MiniLM-L6-v2" | |
| self.tokenizer = AutoTokenizer.from_pretrained(self.backbone_id) | |
| self.models: dict[str, SpecialistModel] = {} | |
| self.load_time_ms: float = 0.0 | |
| t0 = time.perf_counter() | |
| for name in MODEL_DIRS: | |
| mdir = models_root / name | |
| if (mdir / "specialist_int8.onnx").exists() and (mdir / "meta.json").exists(): | |
| self.models[name] = SpecialistModel(mdir, self.tokenizer) | |
| self.load_time_ms = round((time.perf_counter() - t0) * 1000.0, 2) | |
| def list_models(self) -> list[dict[str, Any]]: | |
| out = [] | |
| for name, m in self.models.items(): | |
| size_mb = round(m.onnx_path.stat().st_size / (1024 * 1024), 1) | |
| out.append( | |
| { | |
| "name": name, | |
| "primitive": m.primitive, | |
| "labels": m.labels, | |
| "description": m.description, | |
| "size_mb": size_mb, | |
| "quantization": "INT8 ONNX", | |
| "backbone": m.meta.get("backbone_id", self.backbone_id), | |
| } | |
| ) | |
| return out | |
| AUTH_BLOCK_THRESHOLD = 0.25 | |
| PROMPT_BLOCK_THRESHOLD = 0.16 | |
| def evaluate_auth(self, telemetry_text: str) -> dict[str, Any]: | |
| """Zero-trust login gate using calibrated auth anomaly threshold + multi-model ensemble.""" | |
| auth = self.models["sec_auth_anomaly_gate"].predict(telemetry_text) | |
| severity = self.models["sec_risk_severity"].predict(telemetry_text) | |
| action = self.models["sec_incident_action"].predict(telemetry_text) | |
| indicators = self.models["sec_alert_indicators"].predict(telemetry_text) | |
| iocs = self.models["sec_ioc_extract"].predict(telemetry_text) | |
| ensemble_hit = ( | |
| auth["risk_prob"] >= self.AUTH_BLOCK_THRESHOLD | |
| or severity["severity_level"] >= 4 | |
| or len(indicators["active_tags"]) > 0 | |
| ) | |
| blocked = bool(auth["flagged"]) or ensemble_hit | |
| if not blocked: | |
| action = {**action, "label": "ALLOW_LOG"} | |
| elif action["label"] == "ALLOW_LOG": | |
| action = {**action, "label": "INVESTIGATE_SOC"} | |
| total_ms = round( | |
| auth["latency_ms"] | |
| + severity["latency_ms"] | |
| + action["latency_ms"] | |
| + indicators["latency_ms"] | |
| + iocs["latency_ms"], | |
| 2, | |
| ) | |
| return { | |
| "decision": "BLOCKED" if blocked else "ALLOWED", | |
| "blocked": blocked, | |
| "threshold_used": self.AUTH_BLOCK_THRESHOLD, | |
| "auth_anomaly": auth, | |
| "risk_severity": severity, | |
| "incident_action": action, | |
| "alert_indicators": indicators, | |
| "iocs": iocs, | |
| "total_latency_ms": total_ms, | |
| } | |
| def evaluate_prompt(self, prompt_text: str) -> dict[str, Any]: | |
| """AI Assistant firewall using calibrated prompt injection threshold + secret redaction.""" | |
| injection = self.models["sec_prompt_injection_gate"].predict(prompt_text) | |
| redaction = self.models["sec_log_redact_secrets"].predict(prompt_text) | |
| blocked = bool(injection["flagged"]) or injection["risk_prob"] >= self.PROMPT_BLOCK_THRESHOLD | |
| severity = self.models["sec_risk_severity"].predict(prompt_text) if blocked else None | |
| total_ms = round( | |
| injection["latency_ms"] | |
| + redaction["latency_ms"] | |
| + (severity["latency_ms"] if severity else 0.0), | |
| 2, | |
| ) | |
| return { | |
| "decision": "BLOCKED" if blocked else "ALLOWED", | |
| "blocked": blocked, | |
| "threshold_used": self.PROMPT_BLOCK_THRESHOLD, | |
| "prompt_injection": injection, | |
| "secret_redaction": redaction, | |
| "risk_severity": severity, | |
| "sanitized_prompt": redaction["redacted_text"], | |
| "total_latency_ms": total_ms, | |
| } | |
| def evaluate_log(self, log_text: str) -> dict[str, Any]: | |
| """Full 6-model telemetry ingestion & DLP pipeline with ensemble domain override.""" | |
| redaction = self.models["sec_log_redact_secrets"].predict(log_text) | |
| safe_text = redaction["redacted_text"] | |
| iocs = self.models["sec_ioc_extract"].predict(safe_text) | |
| domain = self.models["sec_domain_router"].predict(safe_text) | |
| indicators = self.models["sec_alert_indicators"].predict(safe_text) | |
| severity = self.models["sec_risk_severity"].predict(safe_text) | |
| action = self.models["sec_incident_action"].predict(safe_text) | |
| # Ensemble safety override: never route high-severity or active-threat events as BENIGN | |
| tags = set(indicators["active_tags"]) | |
| if domain["label"] == "BENIGN" and (severity["severity_level"] >= 4 or tags or redaction["count"] > 0): | |
| if "data_exfiltration" in tags: | |
| override_dom = "NETWORK_TRAFFIC" | |
| elif "lateral_movement" in tags or "defense_evasion" in tags: | |
| override_dom = "HOST_SYSTEM" | |
| else: | |
| override_dom = "APP_IDENTITY" | |
| domain = {**domain, "label": override_dom, "ensemble_override": True} | |
| total_ms = round( | |
| redaction["latency_ms"] | |
| + iocs["latency_ms"] | |
| + domain["latency_ms"] | |
| + indicators["latency_ms"] | |
| + severity["latency_ms"] | |
| + action["latency_ms"], | |
| 2, | |
| ) | |
| return { | |
| "original_length": len(log_text), | |
| "redacted_text": safe_text, | |
| "secrets_found": redaction["count"], | |
| "secret_redaction": redaction, | |
| "iocs": iocs, | |
| "domain": domain, | |
| "alert_indicators": indicators, | |
| "risk_severity": severity, | |
| "incident_action": action, | |
| "total_latency_ms": total_ms, | |
| } | |
| def evaluate_all(self, text: str) -> dict[str, Any]: | |
| """Runs all 8 specialist models on arbitrary text for full SOC inspection.""" | |
| t0 = time.perf_counter() | |
| results = {name: model.predict(text) for name, model in self.models.items()} | |
| total_ms = round((time.perf_counter() - t0) * 1000.0, 2) | |
| return { | |
| "text": text, | |
| "redacted_text": results["sec_log_redact_secrets"]["redacted_text"], | |
| "results": results, | |
| "total_latency_ms": total_ms, | |
| } | |