securegit 0.8.5

Zero-trust git replacement with 12 built-in security scanners, LLM redteam bridge, universal undo, durable backups, and a 50-tool MCP server
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
use crate::core::{Finding, Severity};
use crate::plugins::traits::{PluginError, PluginReport, ScanContext, ScanPhase, SecurityPlugin};
use async_trait::async_trait;
use lazy_static::lazy_static;
use regex::Regex;
use std::path::Path;
use std::time::Instant;

lazy_static! {
    /// Python deserialization patterns.
    static ref PYTHON_DESER_PATTERNS: Vec<(Regex, &'static str, Severity, &'static str)> = vec![
        (
            Regex::new(r"(?i)pickle\.(loads?|Unpickler)\s*\(").unwrap(),
            "Python pickle deserialization (RCE risk)",
            Severity::Critical,
            "pickle.load()/loads() executes arbitrary code during deserialization. \
             Never unpickle untrusted data. CWE-502.",
        ),
        (
            Regex::new(r"(?i)cPickle\.(loads?|Unpickler)\s*\(").unwrap(),
            "Python cPickle deserialization (RCE risk)",
            Severity::Critical,
            "cPickle is the C implementation of pickle and has the same RCE risk. CWE-502.",
        ),
        (
            Regex::new(r"(?i)yaml\.load\s*\(").unwrap(),
            "Python yaml.load() without SafeLoader (RCE risk)",
            Severity::Critical,
            "yaml.load() without Loader=SafeLoader can execute arbitrary Python objects. \
             Use yaml.safe_load() or yaml.load(data, Loader=SafeLoader). CWE-502.",
        ),
        (
            Regex::new(r"(?i)yaml\.unsafe_load\s*\(").unwrap(),
            "Python yaml.unsafe_load() (RCE risk)",
            Severity::Critical,
            "yaml.unsafe_load() explicitly allows arbitrary code execution during YAML parsing. CWE-502.",
        ),
        (
            Regex::new(r"(?i)yaml\.full_load\s*\(").unwrap(),
            "Python yaml.full_load() (potential RCE)",
            Severity::High,
            "yaml.full_load() allows more types than safe_load. Use safe_load for untrusted input.",
        ),
        (
            Regex::new(r"(?i)marshal\.loads?\s*\(").unwrap(),
            "Python marshal deserialization",
            Severity::High,
            "marshal module is not safe for untrusted data. It can crash the interpreter.",
        ),
        (
            Regex::new(r"(?i)shelve\.open\s*\(").unwrap(),
            "Python shelve (uses pickle internally)",
            Severity::High,
            "shelve uses pickle internally and has the same RCE risk for untrusted data. CWE-502.",
        ),
        (
            Regex::new(r"(?i)jsonpickle\.(decode|loads?)\s*\(").unwrap(),
            "Python jsonpickle deserialization (RCE risk)",
            Severity::Critical,
            "jsonpickle can execute arbitrary code during deserialization. CWE-502.",
        ),
    ];

    /// Java deserialization patterns.
    static ref JAVA_DESER_PATTERNS: Vec<(Regex, &'static str, Severity, &'static str)> = vec![
        (
            Regex::new(r"ObjectInputStream\s*\(").unwrap(),
            "Java ObjectInputStream deserialization (RCE risk)",
            Severity::Critical,
            "ObjectInputStream.readObject() can trigger arbitrary code execution \
             via gadget chains (e.g., Commons Collections, Spring). CWE-502.",
        ),
        (
            Regex::new(r"\.readObject\s*\(").unwrap(),
            "Java readObject() call",
            Severity::High,
            "readObject() deserializes Java objects. If the input is untrusted, this enables RCE. CWE-502.",
        ),
        (
            Regex::new(r"\.readUnshared\s*\(").unwrap(),
            "Java readUnshared() call",
            Severity::High,
            "readUnshared() is another deserialization entry point with the same risks as readObject().",
        ),
        (
            Regex::new(r"XMLDecoder\s*\(").unwrap(),
            "Java XMLDecoder deserialization (RCE risk)",
            Severity::Critical,
            "XMLDecoder can execute arbitrary code during XML deserialization. CWE-502.",
        ),
        (
            Regex::new(r"(?i)XStream\s*\(\s*\)").unwrap(),
            "Java XStream default constructor (RCE risk)",
            Severity::Critical,
            "XStream with default settings allows arbitrary code execution. Configure security framework. CWE-502.",
        ),
        (
            Regex::new(r"(?i)Runtime\.getRuntime\(\)\.exec\s*\(").unwrap(),
            "Java Runtime.exec() call",
            Severity::High,
            "Direct command execution. Verify this is not reachable from deserialized input.",
        ),
    ];

    /// XML External Entity (XXE) patterns.
    static ref XXE_PATTERNS: Vec<(Regex, &'static str, Severity, &'static str)> = vec![
        (
            Regex::new(r"(?i)<!ENTITY\s+\w+\s+SYSTEM").unwrap(),
            "XML External Entity (XXE) declaration",
            Severity::Critical,
            "XXE SYSTEM entities can read local files (file://), make SSRF requests, or cause DoS. CWE-611.",
        ),
        (
            Regex::new(r"(?i)<!ENTITY\s+%\s+\w+\s+SYSTEM").unwrap(),
            "XML parameter entity (XXE/SSRF)",
            Severity::Critical,
            "Parameter entities can exfiltrate data via out-of-band channels. CWE-611.",
        ),
        (
            Regex::new(r"(?i)<!DOCTYPE\s+\w+\s+\[").unwrap(),
            "XML inline DTD (potential XXE vector)",
            Severity::Medium,
            "Inline DTDs can declare external entities. Disable DTD processing for untrusted XML.",
        ),
        (
            Regex::new(r"(?i)file:///").unwrap(),
            "Local file reference in XML (XXE payload)",
            Severity::High,
            "file:// URI in XML can read local files via XXE. CWE-611.",
        ),
        (
            Regex::new(r"(?i)FEATURE.*disallow-doctype-decl.*false").unwrap(),
            "XML parser DTD processing not disabled",
            Severity::High,
            "Disallow-doctype-decl set to false allows DTD processing and XXE attacks.",
        ),
    ];

    /// PHP deserialization patterns.
    static ref PHP_DESER_PATTERNS: Vec<(Regex, &'static str, Severity, &'static str)> = vec![
        (
            Regex::new(r"(?i)unserialize\s*\(").unwrap(),
            "PHP unserialize() (object injection risk)",
            Severity::Critical,
            "unserialize() on untrusted data enables PHP Object Injection via magic methods. CWE-502.",
        ),
    ];

    /// Ruby deserialization patterns.
    static ref RUBY_DESER_PATTERNS: Vec<(Regex, &'static str, Severity, &'static str)> = vec![
        (
            Regex::new(r"(?i)Marshal\.load\s*\(").unwrap(),
            "Ruby Marshal.load() (RCE risk)",
            Severity::Critical,
            "Marshal.load() on untrusted data can execute arbitrary code. CWE-502.",
        ),
        (
            Regex::new(r"(?i)YAML\.load\s*\(").unwrap(),
            "Ruby YAML.load() (RCE risk)",
            Severity::Critical,
            "Ruby YAML.load() can instantiate arbitrary objects. Use YAML.safe_load() instead. CWE-502.",
        ),
    ];

    /// .NET deserialization patterns.
    static ref DOTNET_DESER_PATTERNS: Vec<(Regex, &'static str, Severity, &'static str)> = vec![
        (
            Regex::new(r"(?i)BinaryFormatter\s*\(").unwrap(),
            ".NET BinaryFormatter deserialization (RCE risk)",
            Severity::Critical,
            "BinaryFormatter is insecure and deprecated. Use System.Text.Json or a safe alternative. CWE-502.",
        ),
        (
            Regex::new(r"(?i)TypeNameHandling\s*=\s*TypeNameHandling\.(All|Auto|Objects|Arrays)").unwrap(),
            ".NET Json.NET insecure TypeNameHandling",
            Severity::Critical,
            "TypeNameHandling != None allows type instantiation from JSON, enabling RCE. CWE-502.",
        ),
    ];
}

pub struct DeserializationScanner;

impl Default for DeserializationScanner {
    fn default() -> Self {
        Self::new()
    }
}

impl DeserializationScanner {
    pub fn new() -> Self {
        Self
    }

    fn apply_patterns(
        path: &Path,
        content: &str,
        patterns: &[(Regex, &'static str, Severity, &'static str)],
        findings: &mut Vec<Finding>,
    ) {
        for (line_num, line) in content.lines().enumerate() {
            for (pattern, title, severity, description) in patterns.iter() {
                if pattern.is_match(line) {
                    // Suppress yaml.load() if SafeLoader or BaseLoader is present on the same line
                    if title.contains("yaml.load")
                        && (line.contains("SafeLoader") || line.contains("BaseLoader"))
                    {
                        continue;
                    }
                    findings.push(
                        Finding::new(
                            format!("DESER-{:03}", findings.len() + 1),
                            title.to_string(),
                            *severity,
                        )
                        .with_file(path.to_path_buf())
                        .with_line((line_num + 1) as u32)
                        .with_evidence(line.trim().to_string())
                        .with_description(description.to_string()),
                    );
                }
            }
        }
    }
}

#[async_trait]
impl SecurityPlugin for DeserializationScanner {
    fn name(&self) -> &str {
        "deserialization"
    }

    fn version(&self) -> &str {
        "0.1.0"
    }

    fn description(&self) -> &str {
        "Detect unsafe deserialization and XXE vulnerabilities"
    }

    fn scan_phase(&self) -> ScanPhase {
        ScanPhase::All
    }

    async fn initialize(&mut self) -> Result<(), PluginError> {
        Ok(())
    }

    async fn scan(&self, context: &ScanContext<'_>) -> Result<PluginReport, PluginError> {
        let start = Instant::now();
        let mut report = PluginReport::new(self.name().to_string());

        if let Some(content) = context.file_content {
            let content_str = String::from_utf8_lossy(content);
            let ext = context
                .path
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("");

            // Apply language-specific patterns based on file extension
            match ext {
                "py" | "pyw" => {
                    Self::apply_patterns(
                        context.path,
                        &content_str,
                        &PYTHON_DESER_PATTERNS,
                        &mut report.findings,
                    );
                }
                "java" | "kt" | "scala" | "groovy" => {
                    Self::apply_patterns(
                        context.path,
                        &content_str,
                        &JAVA_DESER_PATTERNS,
                        &mut report.findings,
                    );
                }
                "php" | "phtml" => {
                    Self::apply_patterns(
                        context.path,
                        &content_str,
                        &PHP_DESER_PATTERNS,
                        &mut report.findings,
                    );
                }
                "rb" | "erb" => {
                    Self::apply_patterns(
                        context.path,
                        &content_str,
                        &RUBY_DESER_PATTERNS,
                        &mut report.findings,
                    );
                }
                "cs" | "vb" => {
                    Self::apply_patterns(
                        context.path,
                        &content_str,
                        &DOTNET_DESER_PATTERNS,
                        &mut report.findings,
                    );
                }
                _ => {}
            }

            // XXE applies to any XML file or files that may contain XML
            if ext == "xml"
                || ext == "xsl"
                || ext == "xslt"
                || ext == "svg"
                || ext == "xhtml"
                || content_str.trim_start().starts_with("<?xml")
                || content_str.contains("<!DOCTYPE")
            {
                Self::apply_patterns(
                    context.path,
                    &content_str,
                    &XXE_PATTERNS,
                    &mut report.findings,
                );
            }

            if !report.findings.is_empty() {
                report.scanned_files = 1;
            }
        }

        report.duration_ms = start.elapsed().as_millis() as u64;
        Ok(report)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugins::traits::ScanContext;
    use std::collections::HashMap;

    #[tokio::test]
    async fn test_pickle_load() {
        let scanner = DeserializationScanner::new();
        let content = b"data = pickle.loads(request.data)";
        let context = ScanContext {
            path: Path::new("app.py"),
            scan_phase: ScanPhase::PostExtract,
            file_content: Some(content),
            metadata: HashMap::new(),
        };
        let report = scanner.scan(&context).await.unwrap();
        assert!(report.findings.iter().any(|f| f.title.contains("pickle")));
    }

    #[tokio::test]
    async fn test_yaml_load_unsafe() {
        let scanner = DeserializationScanner::new();
        let content = b"config = yaml.load(open('config.yml'))";
        let context = ScanContext {
            path: Path::new("app.py"),
            scan_phase: ScanPhase::PostExtract,
            file_content: Some(content),
            metadata: HashMap::new(),
        };
        let report = scanner.scan(&context).await.unwrap();
        assert!(report
            .findings
            .iter()
            .any(|f| f.title.contains("yaml.load")));
    }

    #[tokio::test]
    async fn test_yaml_safe_load_ok() {
        let scanner = DeserializationScanner::new();
        let content = b"config = yaml.load(data, Loader=SafeLoader)";
        let context = ScanContext {
            path: Path::new("app.py"),
            scan_phase: ScanPhase::PostExtract,
            file_content: Some(content),
            metadata: HashMap::new(),
        };
        let report = scanner.scan(&context).await.unwrap();
        assert!(report
            .findings
            .iter()
            .all(|f| !f.title.contains("yaml.load")));
    }

    #[tokio::test]
    async fn test_xxe_detection() {
        let scanner = DeserializationScanner::new();
        let content =
            br#"<?xml version="1.0"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>"#;
        let context = ScanContext {
            path: Path::new("payload.xml"),
            scan_phase: ScanPhase::PostExtract,
            file_content: Some(content),
            metadata: HashMap::new(),
        };
        let report = scanner.scan(&context).await.unwrap();
        assert!(report.findings.iter().any(|f| f.title.contains("XXE")));
    }

    #[tokio::test]
    async fn test_java_object_input_stream() {
        let scanner = DeserializationScanner::new();
        let content = b"ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());";
        let context = ScanContext {
            path: Path::new("Server.java"),
            scan_phase: ScanPhase::PostExtract,
            file_content: Some(content),
            metadata: HashMap::new(),
        };
        let report = scanner.scan(&context).await.unwrap();
        assert!(report
            .findings
            .iter()
            .any(|f| f.title.contains("ObjectInputStream")));
    }
}