lonkero 3.6.2

Web scanner built for actual pentests. Fast, modular, Rust.
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
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

/**
 * Bountyy Oy - XML Injection Scanner
 * Detects XML injection vulnerabilities
 *
 * Detects:
 * - XML structure manipulation
 * - SOAP injection
 * - XML attribute injection
 * - CDATA injection
 * - XML comment injection
 * - XML namespace manipulation
 *
 * @copyright 2026 Bountyy Oy
 * @license Proprietary
 */
use crate::detection_helpers::AppCharacteristics;
use crate::http_client::HttpClient;
use crate::types::{Confidence, ScanConfig, Severity, Vulnerability};
use std::sync::Arc;
use tracing::{debug, info};

pub struct XMLInjectionScanner {
    http_client: Arc<HttpClient>,
    test_marker: String,
}

impl XMLInjectionScanner {
    pub fn new(http_client: Arc<HttpClient>) -> Self {
        // Generate unique test marker
        let test_marker = format!("xml_{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
        Self {
            http_client,
            test_marker,
        }
    }

    /// Scan endpoint for XML injection vulnerabilities
    pub async fn scan(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        // Intelligent detection - skip for static sites
        if let Ok(response) = self.http_client.get(url).await {
            let characteristics = AppCharacteristics::from_response(&response, url);
            if characteristics.should_skip_injection_tests() {
                info!("[XML] Skipping - static/SPA site detected");
                return Ok((Vec::new(), 0));
            }
        }

        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        info!("[XML] Testing XML injection vulnerabilities");

        // Test XML structure injection
        let (vulns, tests) = self.test_xml_structure_injection(url).await?;
        vulnerabilities.extend(vulns);
        tests_run += tests;

        // Test SOAP injection
        if vulnerabilities.is_empty() {
            let (vulns, tests) = self.test_soap_injection(url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;
        }

        // Test XML attribute injection
        if vulnerabilities.is_empty() {
            let (vulns, tests) = self.test_xml_attribute_injection(url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;
        }

        // Test CDATA injection
        if vulnerabilities.is_empty() {
            let (vulns, tests) = self.test_cdata_injection(url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test XML structure injection
    async fn test_xml_structure_injection(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 4;

        debug!("Testing XML structure injection");

        let payloads = vec![
            format!("</tag><injected>{}</injected><tag>", self.test_marker),
            format!("<tag>{}</tag>", self.test_marker),
            "</user><admin>true</admin><user>".to_string(),
            "</item><price>0</price><item>".to_string(),
        ];

        for payload in payloads {
            let headers = vec![("Content-Type".to_string(), "application/xml".to_string())];

            let xml_body = format!(
                r#"<?xml version="1.0"?><data><value>{}</value></data>"#,
                payload
            );

            match self
                .http_client
                .post_with_headers(url, &xml_body, headers)
                .await
            {
                Ok(response) => {
                    if self.detect_xml_injection(&response.body) {
                        info!("XML structure injection detected");
                        vulnerabilities.push(self.create_vulnerability(
                            url,
                            "XML Structure Injection",
                            &payload,
                            "XML structure can be manipulated via user input",
                            &format!(
                                "XML marker '{}' or structure manipulation detected",
                                self.test_marker
                            ),
                            Severity::High,
                        ));
                        break;
                    }
                }
                Err(e) => {
                    debug!("Request failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test SOAP injection
    async fn test_soap_injection(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 3;

        debug!("Testing SOAP injection");

        let soap_payloads = vec![
            format!(
                r#"</soapenv:Body><soapenv:Body><test>{}</test></soapenv:Body><soapenv:Body>"#,
                self.test_marker
            ),
            "</auth><admin>true</admin><auth>".to_string(),
            r#"</value><value>0</value><value>"#.to_string(),
        ];

        for payload in soap_payloads {
            let headers = vec![
                ("Content-Type".to_string(), "text/xml".to_string()),
                ("SOAPAction".to_string(), "test".to_string()),
            ];

            let soap_body = format!(
                r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <data>{}</data>
    </soapenv:Body>
</soapenv:Envelope>"#,
                payload
            );

            match self
                .http_client
                .post_with_headers(url, &soap_body, headers)
                .await
            {
                Ok(response) => {
                    if self.detect_soap_injection(&response.body) {
                        info!("SOAP injection detected");
                        vulnerabilities.push(self.create_vulnerability(
                            url,
                            "SOAP Injection",
                            &payload,
                            "SOAP message structure can be manipulated",
                            "SOAP structure manipulation detected",
                            Severity::High,
                        ));
                        break;
                    }
                }
                Err(e) => {
                    debug!("SOAP request failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test XML attribute injection
    async fn test_xml_attribute_injection(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 3;

        debug!("Testing XML attribute injection");

        let payloads = vec![
            format!(r#"" admin="true" marker="{}"#, self.test_marker),
            r#"" role="admin"#.to_string(),
            r#""><script>alert(1)</script><tag attr=""#.to_string(),
        ];

        for payload in payloads {
            let headers = vec![("Content-Type".to_string(), "application/xml".to_string())];

            let xml_body = format!(r#"<?xml version="1.0"?><user name="{}" /></user>"#, payload);

            match self
                .http_client
                .post_with_headers(url, &xml_body, headers)
                .await
            {
                Ok(response) => {
                    if self.detect_attribute_injection(&response.body) {
                        info!("XML attribute injection detected");
                        vulnerabilities.push(self.create_vulnerability(
                            url,
                            "XML Attribute Injection",
                            &payload,
                            "XML attributes can be injected or modified",
                            "Attribute injection detected in XML response",
                            Severity::Medium,
                        ));
                        break;
                    }
                }
                Err(e) => {
                    debug!("Request failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test CDATA injection
    async fn test_cdata_injection(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 2;

        debug!("Testing CDATA injection");

        let payloads = vec![
            format!(r#"]]><![CDATA[{}"#, self.test_marker),
            r#"]]></tag><admin>true</admin><tag><![CDATA["#.to_string(),
        ];

        for payload in payloads {
            let headers = vec![("Content-Type".to_string(), "application/xml".to_string())];

            let xml_body = format!(
                r#"<?xml version="1.0"?><data><![CDATA[{}]]></data>"#,
                payload
            );

            match self
                .http_client
                .post_with_headers(url, &xml_body, headers)
                .await
            {
                Ok(response) => {
                    if self.detect_cdata_injection(&response.body) {
                        info!("CDATA injection detected");
                        vulnerabilities.push(self.create_vulnerability(
                            url,
                            "CDATA Injection",
                            &payload,
                            "CDATA section can be broken to inject XML",
                            "CDATA escape detected in response",
                            Severity::Medium,
                        ));
                        break;
                    }
                }
                Err(e) => {
                    debug!("Request failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Detect XML injection in response
    fn detect_xml_injection(&self, body: &str) -> bool {
        // Check for test marker
        if body.contains(&self.test_marker) {
            return true;
        }

        // Check for XML injection indicators
        let indicators = vec![
            "<injected>",
            "<admin>true</admin>",
            "<price>0</price>",
            "xml syntax error",
            "malformed xml",
            "xml parse error",
        ];

        let body_lower = body.to_lowercase();
        for indicator in indicators {
            if body_lower.contains(indicator) {
                return true;
            }
        }

        false
    }

    /// Detect SOAP injection in response
    fn detect_soap_injection(&self, body: &str) -> bool {
        if body.contains(&self.test_marker) {
            return true;
        }

        let body_lower = body.to_lowercase();
        let indicators = vec![
            "soap fault",
            "soap:fault",
            "soapenv:fault",
            "xml parse",
            "malformed soap",
        ];

        for indicator in indicators {
            if body_lower.contains(indicator) {
                return true;
            }
        }

        false
    }

    /// Detect attribute injection
    fn detect_attribute_injection(&self, body: &str) -> bool {
        if body.contains(&self.test_marker) {
            return true;
        }

        let body_lower = body.to_lowercase();
        body_lower.contains(r#"admin="true"#)
            || body_lower.contains(r#"role="admin"#)
            || body_lower.contains("<script>")
    }

    /// Detect CDATA injection
    fn detect_cdata_injection(&self, body: &str) -> bool {
        if body.contains(&self.test_marker) {
            return true;
        }

        let body_lower = body.to_lowercase();
        body_lower.contains("cdata")
            && (body_lower.contains("]]>") || body_lower.contains("<admin>"))
    }

    /// Create a vulnerability record
    fn create_vulnerability(
        &self,
        url: &str,
        attack_type: &str,
        payload: &str,
        description: &str,
        evidence: &str,
        severity: Severity,
    ) -> Vulnerability {
        let cvss = match severity {
            Severity::Critical => 9.1,
            Severity::High => 7.5,
            Severity::Medium => 5.3,
            _ => 3.1,
        };

        Vulnerability {
            id: format!("xml_{}", uuid::Uuid::new_v4().to_string()),
            vuln_type: format!("XML Injection ({})", attack_type),
            severity,
            confidence: Confidence::High,
            category: "Injection".to_string(),
            url: url.to_string(),
            parameter: None,
            payload: payload.to_string(),
            description: description.to_string(),
            evidence: Some(evidence.to_string()),
            cwe: "CWE-91".to_string(),
            cvss: cvss as f32,
            verified: true,
            false_positive: false,
            remediation: "1. Use parameterized XML APIs instead of string concatenation\n\
                         2. Validate and sanitize all user input before XML processing\n\
                         3. Use XML schema validation (XSD) to enforce structure\n\
                         4. Disable XML entity expansion to prevent XXE\n\
                         5. Use safe XML parsing libraries\n\
                         6. Implement input encoding for XML special characters (&, <, >, \", ')\n\
                         7. Use allowlists for acceptable XML values\n\
                         8. Avoid building XML from user input when possible\n\
                         9. Implement proper error handling without revealing XML structure\n\
                         10. Use SOAP message validation for web services"
                .to_string(),
            discovered_at: chrono::Utc::now().to_rfc3339(),
            ml_data: None,
        }
    }
}

// UUID generation helper
mod uuid {
    use rand::Rng;

    pub struct Uuid;

    impl Uuid {
        pub fn new_v4() -> Self {
            Uuid
        }

        pub fn to_string(&self) -> String {
            let mut rng = rand::rng();
            format!(
                "{:08x}{:04x}{:04x}{:04x}{:012x}",
                rng.random::<u32>(),
                rng.random::<u16>(),
                rng.random::<u16>(),
                rng.random::<u16>(),
                rng.random::<u64>() & 0xffffffffffff
            )
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http_client::HttpClient;
    use std::sync::Arc;

    fn create_test_scanner() -> XMLInjectionScanner {
        let http_client = Arc::new(HttpClient::new(30, 3).unwrap());
        XMLInjectionScanner::new(http_client)
    }

    #[test]
    fn test_detect_xml_injection_marker() {
        let scanner = create_test_scanner();
        let body = format!("Response contains {}", scanner.test_marker);

        assert!(scanner.detect_xml_injection(&body));
    }

    #[test]
    fn test_detect_xml_injection_indicators() {
        let scanner = create_test_scanner();

        let bodies = vec![
            "<injected>malicious</injected>",
            "<admin>true</admin>",
            "XML syntax error at line 5",
            "Malformed XML document",
        ];

        for body in bodies {
            assert!(scanner.detect_xml_injection(body));
        }
    }

    #[test]
    fn test_detect_soap_injection() {
        let scanner = create_test_scanner();

        assert!(scanner.detect_soap_injection(&format!("Contains {}", scanner.test_marker)));
        assert!(scanner.detect_soap_injection("SOAP:Fault occurred"));
        assert!(scanner.detect_soap_injection("soapenv:Fault message"));
    }

    #[test]
    fn test_detect_attribute_injection() {
        let scanner = create_test_scanner();

        assert!(scanner.detect_attribute_injection(r#"<user admin="true" />"#));
        assert!(scanner.detect_attribute_injection(r#"role="admin""#));
        assert!(scanner.detect_attribute_injection("<script>alert(1)</script>"));
    }

    #[test]
    fn test_detect_cdata_injection() {
        let scanner = create_test_scanner();

        assert!(scanner.detect_cdata_injection("]]><admin>true</admin><![CDATA["));
        assert!(
            scanner.detect_cdata_injection(&format!("CDATA section with {}", scanner.test_marker))
        );
    }

    #[test]
    fn test_no_false_positives() {
        let scanner = create_test_scanner();
        let body = "Normal XML response without injection";

        assert!(!scanner.detect_xml_injection(body));
        assert!(!scanner.detect_soap_injection(body));
        assert!(!scanner.detect_attribute_injection(body));
        assert!(!scanner.detect_cdata_injection(body));
    }

    #[test]
    fn test_create_vulnerability() {
        let scanner = create_test_scanner();

        let vuln = scanner.create_vulnerability(
            "http://example.com",
            "XML Structure Injection",
            "</tag><injected>test</injected><tag>",
            "XML injection detected",
            "Test evidence",
            Severity::High,
        );

        assert_eq!(vuln.vuln_type, "XML Injection (XML Structure Injection)");
        assert_eq!(vuln.severity, Severity::High);
        assert_eq!(vuln.cwe, "CWE-91");
        assert_eq!(vuln.cvss, 7.5);
        assert!(vuln.verified);
    }

    #[test]
    fn test_unique_test_marker() {
        let scanner1 = create_test_scanner();
        let scanner2 = create_test_scanner();

        assert_ne!(scanner1.test_marker, scanner2.test_marker);
        assert!(scanner1.test_marker.starts_with("xml_"));
    }
}