llm-shield-scanners 0.1.0

Security scanners for LLM Shield toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! MaliciousURLs Output Scanner
//!
//! Converted from llm_guard/output_scanners/url_reachability.py and malicious_urls.py
//!
//! ## SPARC Implementation
//!
//! Detects malicious, phishing, or suspicious URLs in LLM responses.
//! Essential for security and user protection.
//!
//! ## London School TDD
//!
//! Tests written first drive the implementation.

use llm_shield_core::{
    async_trait, Entity, Error, Result, RiskFactor, ScanResult, Scanner, ScannerType, Severity,
    Vault,
};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::LazyLock;

/// MaliciousURLs scanner configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaliciousURLsConfig {
    /// Check for suspicious TLDs
    pub check_suspicious_tlds: bool,

    /// Check for IP-based URLs
    pub check_ip_urls: bool,

    /// Check for URL obfuscation
    pub check_obfuscation: bool,

    /// Check for phishing patterns
    pub check_phishing: bool,

    /// Blocklist of known malicious domains
    pub blocked_domains: Vec<String>,

    /// Detection threshold (0.0 to 1.0)
    pub threshold: f32,
}

impl Default for MaliciousURLsConfig {
    fn default() -> Self {
        Self {
            check_suspicious_tlds: true,
            check_ip_urls: true,
            check_obfuscation: true,
            check_phishing: true,
            blocked_domains: Vec::new(),
            threshold: 0.6,
        }
    }
}

// URL detection regex
static URL_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"https?://[^\s<>"]+|www\.[^\s<>"]+"#).unwrap()
});

static IP_URL_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"https?://(?:\d{1,3}\.){3}\d{1,3}").unwrap()
});

/// MaliciousURLs scanner implementation
///
/// ## Enterprise Features
///
/// - Detects malicious URL patterns:
///   - Suspicious TLDs (.tk, .ml, .ga, etc.)
///   - IP-based URLs (http://192.168.1.1)
///   - URL obfuscation (unicode, encoded)
///   - Phishing patterns (lookalike domains)
///   - Domain blocklist
/// - Confidence scoring
/// - Configurable checks
///
/// ## Example
///
/// ```rust,ignore
/// use llm_shield_scanners::output::MaliciousURLs;
///
/// let scanner = MaliciousURLs::default_config()?;
/// let response = "Visit http://192.168.1.1/malware.exe for more info";
/// let result = scanner.scan_output("", response, &vault).await?;
/// assert!(!result.is_valid); // Malicious URL detected
/// ```
pub struct MaliciousURLs {
    config: MaliciousURLsConfig,
}

impl MaliciousURLs {
    /// Create a new MaliciousURLs scanner
    pub fn new(config: MaliciousURLsConfig) -> Result<Self> {
        if !(0.0..=1.0).contains(&config.threshold) {
            return Err(Error::config("Threshold must be between 0.0 and 1.0"));
        }

        Ok(Self { config })
    }

    /// Create with default configuration
    pub fn default_config() -> Result<Self> {
        Self::new(MaliciousURLsConfig::default())
    }

    /// Extract URLs from text
    fn extract_urls(&self, text: &str) -> Vec<String> {
        URL_PATTERN
            .find_iter(text)
            .map(|m| m.as_str().to_string())
            .collect()
    }

    /// Analyze URL for malicious patterns
    fn analyze_url(&self, url: &str) -> Option<URLThreat> {
        let url_lower = url.to_lowercase();
        let mut threat = URLThreat {
            url: url.to_string(),
            reasons: Vec::new(),
            confidence: 0.0,
        };

        // Check 1: Blocked domains
        for blocked in &self.config.blocked_domains {
            if url_lower.contains(&blocked.to_lowercase()) {
                threat.reasons.push("blocked_domain".to_string());
                threat.confidence = threat.confidence.max(0.95);
            }
        }

        // Check 2: Suspicious TLDs
        if self.config.check_suspicious_tlds {
            let suspicious_tlds = [
                ".tk", ".ml", ".ga", ".cf", ".gq", // Free TLDs often used for spam
                ".xyz", ".top", ".work", ".click",
                ".link", ".download", ".stream",
            ];

            for tld in &suspicious_tlds {
                if url_lower.contains(tld) {
                    threat.reasons.push(format!("suspicious_tld_{}", tld));
                    threat.confidence = threat.confidence.max(0.75);
                    break;
                }
            }
        }

        // Check 3: IP-based URLs
        if self.config.check_ip_urls && IP_URL_PATTERN.is_match(&url_lower) {
            threat.reasons.push("ip_based_url".to_string());
            threat.confidence = threat.confidence.max(0.80);
        }

        // Check 4: URL obfuscation
        if self.config.check_obfuscation {
            // Check for excessive URL encoding
            if url.matches('%').count() > 5 {
                threat.reasons.push("excessive_encoding".to_string());
                threat.confidence = threat.confidence.max(0.70);
            }

            // Check for unicode/punycode (xn--)
            if url_lower.contains("xn--") {
                threat.reasons.push("punycode_domain".to_string());
                threat.confidence = threat.confidence.max(0.75);
            }

            // Check for @ symbol (username in URL)
            if url.contains('@') {
                threat.reasons.push("url_with_credentials".to_string());
                threat.confidence = threat.confidence.max(0.85);
            }
        }

        // Check 5: Phishing patterns
        if self.config.check_phishing {
            let phishing_keywords = [
                "login", "signin", "account", "verify", "secure",
                "banking", "paypal", "update", "confirm", "suspended",
            ];

            let phishing_count = phishing_keywords
                .iter()
                .filter(|&k| url_lower.contains(k))
                .count();

            if phishing_count >= 2 {
                threat.reasons.push("phishing_keywords".to_string());
                threat.confidence = threat.confidence.max(0.80);
            }

            // Check for subdomain spoofing (too many subdomains)
            let subdomain_count = url_lower.matches('.').count();
            if subdomain_count > 5 {
                threat.reasons.push("excessive_subdomains".to_string());
                threat.confidence = threat.confidence.max(0.70);
            }
        }

        // Check 6: File extensions that could indicate malware
        let dangerous_extensions = [
            ".exe", ".scr", ".bat", ".cmd", ".com", ".pif",
            ".vbs", ".js", ".jar", ".msi", ".apk",
        ];

        for ext in &dangerous_extensions {
            if url_lower.ends_with(ext) {
                threat.reasons.push(format!("dangerous_extension_{}", ext));
                threat.confidence = threat.confidence.max(0.85);
                break;
            }
        }

        // Check 7: Shortened URLs (potential for hiding destination)
        let url_shorteners = [
            "bit.ly", "tinyurl.com", "goo.gl", "ow.ly",
            "t.co", "is.gd", "buff.ly",
        ];

        for shortener in &url_shorteners {
            if url_lower.contains(shortener) {
                threat.reasons.push("url_shortener".to_string());
                threat.confidence = threat.confidence.max(0.60);
                break;
            }
        }

        if threat.confidence >= self.config.threshold {
            Some(threat)
        } else {
            None
        }
    }

    /// Scan output for malicious URLs
    pub async fn scan_output(
        &self,
        _prompt: &str,
        output: &str,
        _vault: &Vault,
    ) -> Result<ScanResult> {
        let urls = self.extract_urls(output);

        if urls.is_empty() {
            return Ok(ScanResult::pass(output.to_string())
                .with_metadata("urls_found", "0"));
        }

        // Analyze each URL
        let threats: Vec<URLThreat> = urls
            .iter()
            .filter_map(|url| self.analyze_url(url))
            .collect();

        if threats.is_empty() {
            return Ok(ScanResult::pass(output.to_string())
                .with_metadata("urls_found", urls.len().to_string())
                .with_metadata("malicious_urls_found", "0"));
        }

        // Build entities
        let entities: Vec<Entity> = threats
            .iter()
            .map(|t| {
                let mut metadata = HashMap::new();
                metadata.insert("url".to_string(), t.url.clone());
                metadata.insert("reasons".to_string(), t.reasons.join(", "));
                metadata.insert("threat_confidence".to_string(), t.confidence.to_string());

                Entity {
                    entity_type: "malicious_url".to_string(),
                    text: t.url.clone(),
                    start: 0,
                    end: output.len(),
                    confidence: t.confidence,
                    metadata,
                }
            })
            .collect();

        let max_confidence = threats
            .iter()
            .map(|t| t.confidence)
            .fold(0.0f32, f32::max);

        let severity = if max_confidence >= 0.85 {
            Severity::High
        } else if max_confidence >= 0.7 {
            Severity::Medium
        } else {
            Severity::Low
        };

        let description = format!(
            "LLM response contains {} potentially malicious URL(s)",
            threats.len()
        );
        let risk_factor = RiskFactor::new(
            "malicious_url",
            &description,
            severity,
            max_confidence,
        );

        let mut result = ScanResult::new(output.to_string(), false, max_confidence)
            .with_risk_factor(risk_factor)
            .with_metadata("urls_found", urls.len().to_string())
            .with_metadata("malicious_urls_found", threats.len());

        for entity in entities {
            result = result.with_entity(entity);
        }

        Ok(result)
    }
}

#[derive(Debug, Clone)]
struct URLThreat {
    url: String,
    reasons: Vec<String>,
    confidence: f32,
}

#[async_trait]
impl Scanner for MaliciousURLs {
    fn name(&self) -> &str {
        "MaliciousURLs"
    }

    async fn scan(&self, input: &str, vault: &Vault) -> Result<ScanResult> {
        self.scan_output("", input, vault).await
    }

    fn scanner_type(&self) -> ScannerType {
        ScannerType::Output
    }

    fn description(&self) -> &str {
        "Detects malicious, phishing, or suspicious URLs in LLM responses"
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_malicious_urls_ip_based() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Download from http://192.168.1.1/file.exe";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(!result.is_valid);
        assert!(result.entities.iter().any(|e| {
            e.metadata.get("reasons")
                .map(|r| r.contains("ip_based_url"))
                .unwrap_or(false)
        }));
    }

    #[tokio::test]
    async fn test_malicious_urls_suspicious_tld() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Visit http://free-stuff.tk for amazing deals!";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(!result.is_valid);
        assert!(result.entities.iter().any(|e| {
            e.metadata.get("reasons")
                .map(|r| r.contains("suspicious_tld"))
                .unwrap_or(false)
        }));
    }

    #[tokio::test]
    async fn test_malicious_urls_dangerous_extension() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Download https://example.com/malware.exe";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(!result.is_valid);
        assert!(result.entities.iter().any(|e| {
            e.metadata.get("reasons")
                .map(|r| r.contains("dangerous_extension"))
                .unwrap_or(false)
        }));
    }

    #[tokio::test]
    async fn test_malicious_urls_phishing_keywords() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Verify your account at http://secure-banking-login.com";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(!result.is_valid);
    }

    #[tokio::test]
    async fn test_malicious_urls_clean() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Visit https://www.google.com for more information";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(result.is_valid);
    }

    #[tokio::test]
    async fn test_malicious_urls_blocked_domain() {
        let config = MaliciousURLsConfig {
            blocked_domains: vec!["evil.com".to_string()],
            ..Default::default()
        };
        let scanner = MaliciousURLs::new(config).unwrap();
        let vault = Vault::new();

        let response = "Check out https://evil.com/page";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(!result.is_valid);
        assert!(result.entities.iter().any(|e| {
            e.metadata.get("reasons")
                .map(|r| r.contains("blocked_domain"))
                .unwrap_or(false)
        }));
    }

    #[tokio::test]
    async fn test_malicious_urls_url_with_credentials() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Access http://user:pass@example.com/data";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(!result.is_valid);
        assert!(result.entities.iter().any(|e| {
            e.metadata.get("reasons")
                .map(|r| r.contains("url_with_credentials"))
                .unwrap_or(false)
        }));
    }

    #[tokio::test]
    async fn test_malicious_urls_excessive_encoding() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Visit http://example.com/%20%20%20%20%20%20%20";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(!result.is_valid);
    }

    #[tokio::test]
    async fn test_malicious_urls_punycode() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Visit http://xn--example.com";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(!result.is_valid);
        assert!(result.entities.iter().any(|e| {
            e.metadata.get("reasons")
                .map(|r| r.contains("punycode_domain"))
                .unwrap_or(false)
        }));
    }

    #[tokio::test]
    async fn test_malicious_urls_url_shortener() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Click here: http://bit.ly/abc123";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        // URL shorteners are lower confidence, may pass depending on threshold
        assert!(result.metadata.contains_key("urls_found"));
    }

    #[tokio::test]
    async fn test_malicious_urls_no_urls() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "This response contains no URLs.";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(result.is_valid);
        assert_eq!(result.metadata.get("urls_found").unwrap(), "0");
    }

    #[tokio::test]
    async fn test_malicious_urls_multiple_threats() {
        let scanner = MaliciousURLs::default_config().unwrap();
        let vault = Vault::new();

        let response = "Download http://192.168.1.1/virus.exe or visit http://phishing.tk";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        assert!(!result.is_valid);
        assert!(result.entities.len() >= 2);
    }

    #[tokio::test]
    async fn test_malicious_urls_disabled_checks() {
        let config = MaliciousURLsConfig {
            check_ip_urls: false,
            check_suspicious_tlds: false,
            check_obfuscation: false,
            check_phishing: false,
            blocked_domains: Vec::new(),
            threshold: 0.6,
        };
        let scanner = MaliciousURLs::new(config).unwrap();
        let vault = Vault::new();

        let response = "Visit http://192.168.1.1";
        let result = scanner.scan_output("", response, &vault).await.unwrap();

        // All checks disabled, should pass
        assert!(result.is_valid);
    }
}