agent-shield 1.0.0

Security scanner for AI agent extensions — offline-first, multi-framework, SARIF output
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
use crate::ir::data_surface::{TaintSinkType, TaintSourceType};
use crate::ir::execution_surface::{
    CommandInvocation, FileOpType, FileOperation, NetworkOperation,
};
use crate::ir::{ArgumentSource, ScanTarget};
use crate::rules::{
    AttackCategory, Confidence, Detector, Evidence, Finding, OwaspMcp, RuleMetadata, Severity,
};

/// SHIELD-014: Download-Write-Execute Chain
///
/// Detects when data flows from HTTP download to file write to process execution
/// — a classic supply chain attack pattern (CWE-494).
pub struct DownloadExecDetector;

const SCRIPT_OR_EXECUTABLE_EXTENSIONS: &[&str] = &[
    "appimage", "apk", "bash", "bat", "bin", "cjs", "cmd", "com", "deb", "dmg", "exe", "elf",
    "fish", "jar", "js", "mjs", "msi", "out", "pl", "ps1", "py", "py3", "rb", "rpm", "run", "sh",
    "ts", "tsx", "war", "zsh",
];
const COMMAND_TOKEN_SEPARATORS: &str = "'\";&|()[],";

fn is_download(operation: &NetworkOperation) -> bool {
    !operation.sends_data
        && operation
            .method
            .as_deref()
            .map(|method| method.eq_ignore_ascii_case("GET"))
            .unwrap_or(true)
}

fn is_script_or_executable_path(argument: &ArgumentSource) -> bool {
    let ArgumentSource::Literal(value) = argument else {
        return false;
    };

    let path = value.split(['?', '#']).next().unwrap_or(value);
    let filename = path.rsplit('/').next().unwrap_or(path);
    let Some((_, extension)) = filename.rsplit_once('.') else {
        return false;
    };

    let extension = extension.to_ascii_lowercase();
    SCRIPT_OR_EXECUTABLE_EXTENSIONS
        .iter()
        .any(|candidate| *candidate == extension)
}

fn is_dynamic_path(argument: &ArgumentSource) -> bool {
    matches!(
        argument,
        ArgumentSource::Parameter { .. }
            | ArgumentSource::EnvVar { .. }
            | ArgumentSource::Interpolated
            | ArgumentSource::Unknown
    )
}

fn path_arguments_match(file_path: &ArgumentSource, command: &ArgumentSource) -> bool {
    match (file_path, command) {
        (ArgumentSource::Literal(path), ArgumentSource::Literal(command)) => {
            command == path
                || command
                    .split_whitespace()
                    .map(|token| {
                        token.trim_matches(|character: char| {
                            COMMAND_TOKEN_SEPARATORS.contains(character)
                        })
                    })
                    .any(|token| !token.is_empty() && token == path)
        }
        (
            ArgumentSource::Parameter { name: file_name },
            ArgumentSource::Parameter { name: command_name },
        )
        | (
            ArgumentSource::EnvVar { name: file_name },
            ArgumentSource::EnvVar { name: command_name },
        ) => file_name == command_name,
        _ => false,
    }
}

fn find_executed_write(target: &ScanTarget) -> Option<(&FileOperation, &CommandInvocation)> {
    target
        .execution
        .file_operations
        .iter()
        .filter(|file_op| file_op.operation == FileOpType::Write)
        .find_map(|file_op| {
            let path_is_script = is_script_or_executable_path(&file_op.path_arg);
            let path_is_dynamic = is_dynamic_path(&file_op.path_arg);

            target.execution.commands.iter().find_map(|command| {
                (path_arguments_match(&file_op.path_arg, &command.command_arg)
                    && (path_is_script || path_is_dynamic))
                    .then_some((file_op, command))
            })
        })
}

impl Detector for DownloadExecDetector {
    fn metadata(&self) -> RuleMetadata {
        RuleMetadata {
            id: "SHIELD-014".into(),
            name: "Download-Write-Execute Chain".into(),
            description: "Data flows from HTTP download to file write to process execution \
                          — classic supply chain attack pattern"
                .into(),
            default_severity: Severity::Critical,
            attack_category: AttackCategory::SupplyChain,
            cwe_id: Some("CWE-494".into()),
            owasp_mcp: Some(OwaspMcp::SupplyChain),
        }
    }

    fn run(&self, target: &ScanTarget) -> Vec<Finding> {
        let mut findings = Vec::new();

        // Phase 1: Check taint paths for HttpResponse -> FileWrite chains,
        // then look for a ProcessExec sink in the same target.
        let has_http_to_file = target.data.taint_paths.iter().any(|p| {
            matches!(p.source.source_type, TaintSourceType::HttpResponse)
                && matches!(p.sink.sink_type, TaintSinkType::FileWrite)
        });

        let has_process_exec_sink = target
            .data
            .taint_paths
            .iter()
            .any(|p| matches!(p.sink.sink_type, TaintSinkType::ProcessExec));

        if has_http_to_file && has_process_exec_sink {
            // Find the specific paths to build evidence
            let http_to_file = target.data.taint_paths.iter().find(|p| {
                matches!(p.source.source_type, TaintSourceType::HttpResponse)
                    && matches!(p.sink.sink_type, TaintSinkType::FileWrite)
            });

            let file_to_exec = target
                .data
                .taint_paths
                .iter()
                .find(|p| matches!(p.sink.sink_type, TaintSinkType::ProcessExec));

            let mut evidence = Vec::new();
            let mut location = None;

            if let Some(path) = http_to_file {
                evidence.push(Evidence {
                    description: format!("HTTP download: '{}'", path.source.description),
                    location: Some(path.source.location.clone()),
                    snippet: None,
                });
                evidence.push(Evidence {
                    description: format!("File write: '{}'", path.sink.description),
                    location: Some(path.sink.location.clone()),
                    snippet: None,
                });
            }

            if let Some(path) = file_to_exec {
                location = Some(path.sink.location.clone());
                evidence.push(Evidence {
                    description: format!("Process execution: '{}'", path.sink.description),
                    location: Some(path.sink.location.clone()),
                    snippet: None,
                });
            }

            findings.push(Finding {
                rule_id: "SHIELD-014".into(),
                rule_name: "Download-Write-Execute Chain".into(),
                severity: Severity::Critical,
                confidence: Confidence::High,
                attack_category: AttackCategory::SupplyChain,
                message: "Detected download-write-execute chain: HTTP response flows to \
                          file write, and a process execution sink exists in the same scope"
                    .into(),
                location,
                evidence,
                taint_path: None,
                remediation: Some(
                    "Verify downloaded content integrity using checksums or signatures \
                     before writing to disk. Never execute downloaded files directly. \
                     Use package managers with lockfiles instead of custom download logic."
                        .into(),
                ),
                cwe_id: Some("CWE-494".into()),
            });
        }

        // Phase 2: conservative fallback for parsers that cannot build a taint path.
        // Require a download-like request and execution of the same script/executable
        // path that was written. Dynamic paths are retained because they cannot be
        // classified by extension, but must still match between the write and exec.
        if findings.is_empty() {
            if let Some(network) = target
                .execution
                .network_operations
                .iter()
                .find(|operation| is_download(operation))
            {
                if let Some((file_op, command)) = find_executed_write(target) {
                    let mut evidence = vec![Evidence {
                        description: format!("Network operation: '{}'", network.function),
                        location: Some(network.location.clone()),
                        snippet: None,
                    }];
                    evidence.push(Evidence {
                        description: "File write operation".into(),
                        location: Some(file_op.location.clone()),
                        snippet: None,
                    });
                    evidence.push(Evidence {
                        description: format!("Command execution: '{}'", command.function),
                        location: Some(command.location.clone()),
                        snippet: None,
                    });

                    findings.push(Finding {
                        rule_id: "SHIELD-014".into(),
                        rule_name: "Download-Write-Execute Chain".into(),
                        severity: Severity::Critical,
                        confidence: Confidence::Medium,
                        attack_category: AttackCategory::SupplyChain,
                        message: "Potential download-write-execute chain: a downloaded script or \
                                  executable is written and the same path is executed"
                            .into(),
                        location: Some(command.location.clone()),
                        evidence,
                        taint_path: None,
                        remediation: Some(
                            "Verify downloaded content integrity using checksums or signatures \
                             before writing to disk. Never execute downloaded files directly. \
                             Use package managers with lockfiles instead of custom download logic."
                                .into(),
                        ),
                        cwe_id: Some("CWE-494".into()),
                    });
                }
            }
        }

        findings
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::data_surface::*;
    use crate::ir::execution_surface::*;
    use crate::ir::*;
    use std::path::PathBuf;

    fn loc() -> SourceLocation {
        SourceLocation {
            file: PathBuf::from("test.py"),
            line: 5,
            column: 0,
            end_line: None,
            end_column: None,
        }
    }

    fn empty_target() -> ScanTarget {
        ScanTarget {
            name: "test".into(),
            framework: Framework::Mcp,
            root_path: PathBuf::from("."),
            tools: vec![],
            execution: ExecutionSurface::default(),
            data: DataSurface::default(),
            dependencies: Default::default(),
            provenance: Default::default(),
            source_files: vec![],
        }
    }

    #[test]
    fn detects_download_write_exec_via_taint_paths() {
        let mut target = empty_target();

        // HTTP response -> file write
        target.data.taint_paths.push(TaintPath {
            source: TaintSource {
                source_type: TaintSourceType::HttpResponse,
                description: "requests.get response".into(),
                location: loc(),
            },
            sink: TaintSink {
                sink_type: TaintSinkType::FileWrite,
                description: "open('/tmp/script.sh', 'w')".into(),
                location: loc(),
            },
            through: vec![],
            confidence: 0.9,
        });

        // File content -> process exec
        target.data.taint_paths.push(TaintPath {
            source: TaintSource {
                source_type: TaintSourceType::FileContent,
                description: "script.sh".into(),
                location: loc(),
            },
            sink: TaintSink {
                sink_type: TaintSinkType::ProcessExec,
                description: "subprocess.run".into(),
                location: loc(),
            },
            through: vec![],
            confidence: 0.9,
        });

        let findings = DownloadExecDetector.run(&target);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule_id, "SHIELD-014");
        assert_eq!(findings[0].severity, Severity::Critical);
        assert_eq!(findings[0].confidence, Confidence::High);
        assert_eq!(findings[0].evidence.len(), 3);
    }

    #[test]
    fn detects_download_write_exec_via_execution_surface() {
        let mut target = empty_target();

        target.execution.network_operations.push(NetworkOperation {
            function: "requests.get".into(),
            url_arg: ArgumentSource::Literal("https://example.com/script.sh".into()),
            method: Some("GET".into()),
            sends_data: false,
            location: loc(),
        });

        target.execution.file_operations.push(FileOperation {
            operation: FileOpType::Write,
            path_arg: ArgumentSource::Literal("/tmp/script.sh".into()),
            location: loc(),
        });

        target.execution.commands.push(CommandInvocation {
            function: "subprocess.run".into(),
            command_arg: ArgumentSource::Literal("/tmp/script.sh".into()),
            location: loc(),
        });

        let findings = DownloadExecDetector.run(&target);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule_id, "SHIELD-014");
        assert_eq!(findings[0].confidence, Confidence::Medium);
    }

    #[test]
    fn does_not_detect_without_taint_chain() {
        let mut target = empty_target();

        target.execution.network_operations.push(NetworkOperation {
            function: "requests.get".into(),
            url_arg: ArgumentSource::Parameter { name: "url".into() },
            method: Some("GET".into()),
            sends_data: false,
            location: loc(),
        });

        target.execution.file_operations.push(FileOperation {
            operation: FileOpType::Write,
            path_arg: ArgumentSource::Parameter {
                name: "output_path".into(),
            },
            location: loc(),
        });

        target.execution.commands.push(CommandInvocation {
            function: "subprocess.run".into(),
            command_arg: ArgumentSource::Parameter {
                name: "command".into(),
            },
            location: loc(),
        });

        let findings = DownloadExecDetector.run(&target);
        assert!(findings.is_empty());
    }

    #[test]
    fn no_finding_for_unrelated_non_executable_write() {
        let mut target = empty_target();

        target.execution.network_operations.push(NetworkOperation {
            function: "requests.get".into(),
            url_arg: ArgumentSource::Literal("https://example.com/data.json".into()),
            method: Some("GET".into()),
            sends_data: false,
            location: loc(),
        });

        target.execution.file_operations.push(FileOperation {
            operation: FileOpType::Write,
            path_arg: ArgumentSource::Literal("/tmp/data.json".into()),
            location: loc(),
        });

        target.execution.commands.push(CommandInvocation {
            function: "subprocess.run".into(),
            command_arg: ArgumentSource::Literal("ls -la".into()),
            location: loc(),
        });

        let findings = DownloadExecDetector.run(&target);
        assert!(findings.is_empty());
    }

    #[test]
    fn no_finding_when_execution_targets_a_different_path() {
        let mut target = empty_target();

        target.execution.network_operations.push(NetworkOperation {
            function: "requests.get".into(),
            url_arg: ArgumentSource::Literal("https://example.com/script.sh".into()),
            method: Some("GET".into()),
            sends_data: false,
            location: loc(),
        });

        target.execution.file_operations.push(FileOperation {
            operation: FileOpType::Write,
            path_arg: ArgumentSource::Literal("/tmp/script.sh".into()),
            location: loc(),
        });

        target.execution.commands.push(CommandInvocation {
            function: "subprocess.run".into(),
            command_arg: ArgumentSource::Literal("/tmp/other.sh".into()),
            location: loc(),
        });

        let findings = DownloadExecDetector.run(&target);
        assert!(findings.is_empty());
    }

    #[test]
    fn detects_dynamic_path_when_write_and_exec_share_argument() {
        let mut target = empty_target();

        target.execution.network_operations.push(NetworkOperation {
            function: "requests.get".into(),
            url_arg: ArgumentSource::Parameter { name: "url".into() },
            method: Some("GET".into()),
            sends_data: false,
            location: loc(),
        });

        let output_path = ArgumentSource::Parameter {
            name: "output_path".into(),
        };
        target.execution.file_operations.push(FileOperation {
            operation: FileOpType::Write,
            path_arg: output_path.clone(),
            location: loc(),
        });
        target.execution.commands.push(CommandInvocation {
            function: "subprocess.run".into(),
            command_arg: output_path,
            location: loc(),
        });

        let findings = DownloadExecDetector.run(&target);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].confidence, Confidence::Medium);
    }

    #[test]
    fn no_finding_without_write() {
        let mut target = empty_target();

        target.execution.network_operations.push(NetworkOperation {
            function: "requests.get".into(),
            url_arg: ArgumentSource::Literal("https://api.example.com/data".into()),
            method: Some("GET".into()),
            sends_data: false,
            location: loc(),
        });

        target.execution.commands.push(CommandInvocation {
            function: "subprocess.run".into(),
            command_arg: ArgumentSource::Literal("ls -la".into()),
            location: loc(),
        });

        // No file write — should not trigger
        let findings = DownloadExecDetector.run(&target);
        assert!(findings.is_empty());
    }
}