""" CSV Injection Detection Service for MalwareGuard. Analyzes uploaded CSV files for formula injection, DDE attacks, and other threats. Supports 30 features, threat localization, and multi-class classification. """ import csv import hashlib import io import logging import math import re from collections import Counter from pathlib import Path from typing import Optional, List, Dict, Any import joblib import numpy as np logger = logging.getLogger(__name__) # ── Feature extraction constants ───────────────────────────────────────────── FORMULA_TRIGGERS = {"=", "+", "-", "@"} FULL_WIDTH_TRIGGERS = {"=", "+", "-"} CONTROL_CHARS = {"\t", "\r", "\n"} DANGEROUS_KEYWORDS = [ "cmd", "powershell", "exec", "system", "shell", "wscript", "cscript", "mshta", "rundll32", "certutil", "bitsadmin", "schtasks", "wmic", "reg ", "net user", "net localgroup", ] DANGEROUS_FUNCTIONS = [ "hyperlink", "importxml", "importdata", "importhtml", "importfeed", "webservice", "call", "register", "exec", "system", "image", "indirect", "concatenate", "char(", "iferror", "choose", "if(", ] # 30 Feature columns FEATURE_COLS = [ "file_size", "row_count", "col_count", "total_cells", "formula_trigger_cells", "fullwidth_trigger_cells", "control_prefix_cells", "formula_cell_ratio", "dangerous_keyword_count", "dangerous_function_count", "pipe_count", "exclamation_count", "url_count", "path_reference_count", "entropy", "avg_cell_length", "max_cell_length", # 13 New Features: "nested_function_depth", "base64_pattern_count", "unicode_homoglyph_count", "env_variable_count", "data_uri_count", "macro_indicator_count", "suspicious_encoding_ratio", "cell_length_variance", "header_has_formula", "first_col_formula_ratio", "empty_cell_ratio", "concatenate_count", "char_function_count", ] # Regex patterns BASE64_REGEX = re.compile(r'[A-Za-z0-9+/]{16,}={0,2}') ENV_REGEX = re.compile(r'%[A-Za-z0-9_]{2,}%') HOMOGLYPH_CHARS = set("аеорсхуіѕіїєАЕОРСХУІЅІЇЄ") MACRO_KEYWORDS = ["auto_open", "workbook_open", "document_open", "macro", "vba_", "run_macro", "stdcall"] INJECTION_CLASSES = [ "benign", "dde", "obfuscated", "formula_import", "hyperlink", "macro", "chained", "env_exploit", "cmd_exec", "data_uri", "multi_cell" ] class CSVAnalysisResult: """Result of CSV file analysis.""" def __init__( self, verdict: str, probability: float, confidence: str, threats_found: List[Dict[str, str]], file_metadata: Dict[str, Any], features: Dict[str, Any], injection_type: str = "none", threat_locations: List[Dict[str, Any]] = None, ): self.verdict = verdict self.probability = probability self.confidence = confidence self.threats_found = threats_found self.file_metadata = file_metadata self.features = features self.injection_type = injection_type self.threat_locations = threat_locations or [] def to_dict(self) -> dict: return { "verdict": self.verdict, "probability": self.probability, "confidence": self.confidence, "threats_found": self.threats_found, "file_metadata": self.file_metadata, "features": self.features, "injection_type": self.injection_type, "threat_locations": self.threat_locations, } class CSVAnalyzerService: """Service for analyzing CSV files for injection attacks.""" def __init__(self): self.model = None self.multiclass_model = None self.model_loaded = False self.multiclass_model_loaded = False self._load_model() def _load_model(self): models_dir = Path(__file__).parent.parent / "ml_models" model_path = models_dir / "csv_injection_model.joblib" multiclass_path = models_dir / "csv_injection_multiclass_model.joblib" try: self.model = joblib.load(model_path) self.model_loaded = True logger.info(f"CSV injection binary model loaded from {model_path}") except Exception as e: logger.warning(f"CSV injection binary model not found at {model_path}: {e}") self.model_loaded = False try: self.multiclass_model = joblib.load(multiclass_path) self.multiclass_model_loaded = True logger.info(f"CSV injection multiclass model loaded from {multiclass_path}") except Exception as e: logger.warning(f"CSV injection multiclass model not found at {multiclass_path}: {e}") self.multiclass_model_loaded = False def analyze(self, content: bytes, filename: str) -> CSVAnalysisResult: """Analyze a CSV file for injection attacks.""" # Reject files larger than 50 MB to prevent resource exhaustion if len(content) > 50 * 1024 * 1024: return CSVAnalysisResult( verdict="Error", probability=0.0, confidence="High", threats_found=[], file_metadata={ "filename": filename, "sha256": "", "file_size": len(content), "row_count": 0, "col_count": 0, "total_cells": 0, "error": "File exceeds 50 MB size limit", }, features={col: 0 for col in FEATURE_COLS}, injection_type="none", threat_locations=[], ) raw = content.decode("utf-8", errors="replace") sha256 = hashlib.sha256(content).hexdigest() # Parse CSV rows = [] try: reader = csv.reader(io.StringIO(raw)) for row in reader: rows.append(row) except csv.Error as e: logger.warning(f"CSV parsing error for {filename}: {e}") # Continue with whatever rows were successfully parsed # Extract features features = self._extract_features(raw, rows, len(content)) # Rule-based threat detection & localization threats, threat_locations = self._detect_threats_and_localize(raw, rows) # ML prediction mal_prob = 0.0 injection_type = "none" if self.model_loaded: feature_vector = np.array( [features[col] for col in FEATURE_COLS], dtype=np.float32 ).reshape(1, -1) try: # Support models trained with either 17 or 30 features n_features = 17 if hasattr(self.model, "n_features_in_"): n_features = self.model.n_features_in_ elif hasattr(self.model, "feature_importances_"): n_features = len(self.model.feature_importances_) if n_features == 17: # Legacy 17 feature model compatibility legacy_cols = FEATURE_COLS[:17] legacy_vector = np.array( [features[col] for col in legacy_cols], dtype=np.float32 ).reshape(1, -1) proba = self.model.predict_proba(legacy_vector) else: proba = self.model.predict_proba(feature_vector) mal_prob = float(proba[0][1]) except Exception as e: logger.error(f"Binary CSV prediction error: {e}") mal_prob = 1.0 if threats else 0.0 else: mal_prob = 1.0 if threats else 0.0 if self.multiclass_model_loaded and mal_prob >= 0.5: feature_vector = np.array( [features[col] for col in FEATURE_COLS], dtype=np.float32 ).reshape(1, -1) try: pred_class_idx = int(self.multiclass_model.predict(feature_vector)[0]) if 0 <= pred_class_idx < len(INJECTION_CLASSES): injection_type = INJECTION_CLASSES[pred_class_idx] except Exception as e: logger.error(f"Multiclass CSV prediction error: {e}") # Determine final verdict if mal_prob >= 0.5 or len(threats) > 0: verdict = "Malicious" if injection_type == "none" and threats: # Map heuristic threats to best guest injection type t_types = [t["type"] for t in threats] if "DDE Command Execution" in t_types: injection_type = "dde" elif "Formula Injection" in t_types: injection_type = "formula_import" elif "Command Execution Payload" in t_types: injection_type = "cmd_exec" elif "Obfuscation Detected" in t_types: injection_type = "obfuscated" else: injection_type = "hyperlink" else: verdict = "Benign" injection_type = "none" # Confidence distance = abs(mal_prob - 0.5) if distance >= 0.3: confidence = "High" elif distance >= 0.15: confidence = "Medium" else: confidence = "Low" file_metadata = { "filename": filename, "sha256": sha256, "file_size": len(content), "row_count": len(rows), "col_count": len(rows[0]) if rows else 0, "total_cells": sum(len(r) for r in rows), } return CSVAnalysisResult( verdict=verdict, probability=round(mal_prob, 4), confidence=confidence, threats_found=threats, file_metadata=file_metadata, features=features, injection_type=injection_type, threat_locations=threat_locations, ) def _extract_features(self, raw: str, rows: list, file_size: int) -> dict: total_cells = sum(len(r) for r in rows) all_cells = [cell for row in rows for cell in row] raw_lower = raw.lower() # Legacy features formula_cells = sum(1 for c in all_cells if c and c[0] in FORMULA_TRIGGERS) fullwidth_cells = sum(1 for c in all_cells if c and c[0] in FULL_WIDTH_TRIGGERS) control_prefix = sum(1 for c in all_cells if c and c[0] in CONTROL_CHARS) keyword_hits = sum(1 for kw in DANGEROUS_KEYWORDS if kw in raw_lower) function_hits = sum(1 for fn in DANGEROUS_FUNCTIONS if fn in raw_lower) pipe_count = raw.count("|") excl_count = raw.count("!") url_count = raw_lower.count("http://") + raw_lower.count("https://") + raw_lower.count("ftp://") path_count = raw_lower.count("c:\\") + raw_lower.count("%temp%") + raw_lower.count("%appdata%") if raw: freq = Counter(raw) length = len(raw) entropy = -sum((c / length) * math.log2(c / length) for c in freq.values() if c > 0) else: entropy = 0.0 # New Features calculations nested_function_depth = 0 for cell in all_cells: if cell and any(cell.startswith(t) for t in FORMULA_TRIGGERS): current_depth = 0 max_cell_depth = 0 for char in cell: if char == '(': current_depth += 1 if current_depth > max_cell_depth: max_cell_depth = current_depth elif char == ')': current_depth = max(0, current_depth - 1) if max_cell_depth > nested_function_depth: nested_function_depth = max_cell_depth base64_pattern_count = sum(len(BASE64_REGEX.findall(c)) for c in all_cells if c) unicode_homoglyph_count = sum(1 for c in raw if c in HOMOGLYPH_CHARS) env_variable_count = sum(len(ENV_REGEX.findall(c)) for c in all_cells if c) data_uri_count = sum(1 for c in all_cells if c and "data:" in c.lower()) macro_indicator_count = sum(1 for kw in MACRO_KEYWORDS if kw in raw_lower) non_ascii = sum(1 for c in raw if ord(c) > 127) suspicious_encoding_ratio = non_ascii / len(raw) if raw else 0.0 cell_lengths = [len(c) for c in all_cells] if len(cell_lengths) > 1: mean = sum(cell_lengths) / len(cell_lengths) cell_length_variance = sum((x - mean) ** 2 for x in cell_lengths) / (len(cell_lengths) - 1) else: cell_length_variance = 0.0 first_row = rows[0] if rows else [] header_has_formula = 1.0 if any(c and c[0] in FORMULA_TRIGGERS for c in first_row) else 0.0 first_col = [row[0] for row in rows if row] formula_in_first_col = sum(1 for c in first_col if c and c[0] in FORMULA_TRIGGERS) first_col_formula_ratio = formula_in_first_col / len(first_col) if first_col else 0.0 empty_cells = sum(1 for c in all_cells if not c or c.strip() == "") empty_cell_ratio = empty_cells / total_cells if total_cells else 0.0 concatenate_count = raw_lower.count("concatenate") + raw_lower.count("concat(") char_function_count = raw_lower.count("char(") return { "file_size": file_size, "row_count": len(rows), "col_count": len(rows[0]) if rows else 0, "total_cells": total_cells, "formula_trigger_cells": formula_cells, "fullwidth_trigger_cells": fullwidth_cells, "control_prefix_cells": control_prefix, "formula_cell_ratio": formula_cells / total_cells if total_cells else 0.0, "dangerous_keyword_count": keyword_hits, "dangerous_function_count": function_hits, "pipe_count": pipe_count, "exclamation_count": excl_count, "url_count": url_count, "path_reference_count": path_count, "entropy": round(entropy, 4), "avg_cell_length": round(sum(cell_lengths) / total_cells, 2) if total_cells else 0, "max_cell_length": max(cell_lengths, default=0), # New 13 features: "nested_function_depth": nested_function_depth, "base64_pattern_count": base64_pattern_count, "unicode_homoglyph_count": unicode_homoglyph_count, "env_variable_count": env_variable_count, "data_uri_count": data_uri_count, "macro_indicator_count": macro_indicator_count, "suspicious_encoding_ratio": round(suspicious_encoding_ratio, 4), "cell_length_variance": round(cell_length_variance, 4), "header_has_formula": header_has_formula, "first_col_formula_ratio": round(first_col_formula_ratio, 4), "empty_cell_ratio": round(empty_cell_ratio, 4), "concatenate_count": concatenate_count, "char_function_count": char_function_count, } def _detect_threats_and_localize(self, raw: str, rows: list) -> tuple: """Rule-based threat detection and threat cell localization.""" threats = [] threat_locations = [] raw_lower = raw.lower() # DDE attacks if "cmd|" in raw_lower or "msexcel|" in raw_lower: threats.append({ "type": "DDE Command Execution", "severity": "Critical", "description": "Dynamic Data Exchange (DDE) payload detected — can execute system commands when opened in Excel.", }) # Dangerous functions dangerous_funcs_found = [fn for fn in ["hyperlink", "importxml", "importdata", "webservice", "importfeed"] if fn in raw_lower] if dangerous_funcs_found: threats.append({ "type": "Formula Injection", "severity": "High", "description": f"Dangerous spreadsheet functions detected: {', '.join(dangerous_funcs_found)}", }) # System command keywords cmd_keywords = [kw for kw in ["powershell", "certutil", "bitsadmin", "mshta", "rundll32", "schtasks"] if kw in raw_lower] if cmd_keywords: threats.append({ "type": "Command Execution Payload", "severity": "Critical", "description": f"System command keywords found: {', '.join(cmd_keywords)}", }) # Full-width character obfuscation if any(c in raw for c in FULL_WIDTH_TRIGGERS): threats.append({ "type": "Obfuscation Detected", "severity": "Medium", "description": "Full-width Unicode characters used to bypass formula injection filters.", }) # Embedded URLs url_count = raw_lower.count("http://") + raw_lower.count("https://") if url_count > 0 and any(kw in raw_lower for kw in ["evil", "malware", "phish", "steal", "exfil"]): threats.append({ "type": "Suspicious URLs", "severity": "High", "description": f"Found {url_count} embedded URLs with suspicious keywords.", }) # Localize specific cells triggering issues for r_idx, row in enumerate(rows): for c_idx, cell in enumerate(row): if not cell: continue cell_lower = cell.lower() reasons = [] # DDE Check if "cmd|" in cell_lower or "msexcel|" in cell_lower: reasons.append("Contains DDE command execution payload") # Formula trigger + dangerous function if any(cell.startswith(t) for t in FORMULA_TRIGGERS): for fn in ["hyperlink", "importxml", "importdata", "webservice", "importfeed", "call", "register"]: if fn in cell_lower: reasons.append(f"Uses dangerous function '{fn}' in formula") # Full-width triggers if any(c in cell for c in FULL_WIDTH_TRIGGERS): reasons.append("Uses obfuscated full-width trigger characters") # Char functions if "char(" in cell_lower: reasons.append("Uses CHAR() function to obfuscate string patterns") # System command keywords for kw in ["powershell", "certutil", "bitsadmin", "mshta", "rundll32", "schtasks"]: if kw in cell_lower: reasons.append(f"Contains system command keyword '{kw}'") # Suspicious URL if ("http://" in cell_lower or "https://" in cell_lower) and any(kw in cell_lower for kw in ["evil", "malware", "phish", "steal", "exfil"]): reasons.append("Contains highly suspicious external URL link") # Environment variables if ENV_REGEX.search(cell): reasons.append("References system environment variables") if reasons: preview = cell[:50] + "..." if len(cell) > 50 else cell threat_locations.append({ "row": r_idx + 1, "col": c_idx + 1, "preview": preview, "reasons": reasons }) return threats, threat_locations # Singleton _csv_analyzer: Optional[CSVAnalyzerService] = None def get_csv_analyzer() -> CSVAnalyzerService: global _csv_analyzer if _csv_analyzer is None: _csv_analyzer = CSVAnalyzerService() return _csv_analyzer