leaktor 0.4.1

A secrets scanner with pattern matching, entropy analysis, and live validation
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
//! Docker image scanner -- pull an image, export its filesystem, and scan for secrets.
//!
//! Requires the `docker` feature flag (enabled by default) and a running Docker daemon.
//!
//! The scanner:
//!   1. Pulls the image (or uses a locally available one)
//!   2. Creates a temporary container (never started)
//!   3. Exports the container filesystem as a tar stream
//!   4. Extracts text files from the tar and scans them
//!   5. Cleans up the temporary container
//!
//! Usage:
//!   leaktor scan-docker myapp:latest
//!   leaktor scan-docker ghcr.io/org/repo:v1.2.3

use crate::detectors::{ContextAnalyzer, PatternDetector};
use crate::models::{Context, Finding, Location};
use crate::scan_warn;
use anyhow::Result;
use std::path::PathBuf;

/// Maximum individual file size to scan inside a Docker image (2 MB).
const MAX_FILE_SIZE: usize = 2 * 1024 * 1024;

/// File extensions that are always skipped (binary / non-text).
const BINARY_EXTENSIONS: &[&str] = &[
    "zip", "tar", "gz", "bz2", "xz", "7z", "rar", "zst", "lz4", "exe", "dll", "so", "dylib",
    "bin", "jpg", "jpeg", "png", "gif", "bmp", "ico", "svg", "webp", "tiff", "avif", "mp3",
    "mp4", "avi", "mov", "mkv", "flac", "wav", "ogg", "webm", "woff", "woff2", "ttf", "eot",
    "otf", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "dat", "db", "sqlite", "sqlite3",
    "parquet", "arrow", "iso", "img", "dmg", "vmdk", "map", "o", "a", "lib", "obj", "class",
    "pyc",
];

/// Paths inside container images that almost never contain user secrets.
const SKIP_PREFIXES: &[&str] = &[
    "usr/share/doc/",
    "usr/share/man/",
    "usr/share/locale/",
    "usr/share/zoneinfo/",
    "usr/share/i18n/",
    "usr/share/terminfo/",
    "usr/lib/",
    "usr/lib64/",
    "lib/",
    "lib64/",
    "proc/",
    "sys/",
    "dev/",
    "run/",
    "var/cache/",
    "var/log/",
];

/// Files that contain legitimate cryptographic material (CA certificates, key
/// stores) and are notorious sources of false positives when scanning Docker
/// images.  These files match certificate/key patterns but are public trust
/// anchors, not secrets.
const SKIP_FILES: &[&str] = &[
    "etc/ssl/certs/ca-certificates.crt",
    "etc/ssl/certs/ca-bundle.crt",
    "etc/ssl/cert.pem",
    "etc/pki/tls/certs/ca-bundle.crt",
    "etc/pki/tls/certs/ca-bundle.trust.crt",
    "etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
    "etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt",
    "usr/share/ca-certificates/",
    "etc/ca-certificates/",
];

/// Scanner for Docker container images.
pub struct DockerScanner {
    image: String,
    entropy_threshold: f64,
    custom_patterns: Vec<crate::config::settings::CustomPattern>,
    /// If true, attempt to pull the image before scanning (default: true).
    pull: bool,
}

impl DockerScanner {
    pub fn new(image: String) -> Self {
        Self {
            image,
            entropy_threshold: 3.5,
            custom_patterns: Vec::new(),
            pull: true,
        }
    }

    pub fn with_entropy_threshold(mut self, threshold: f64) -> Self {
        self.entropy_threshold = threshold;
        self
    }

    pub fn with_custom_patterns(
        mut self,
        patterns: Vec<crate::config::settings::CustomPattern>,
    ) -> Self {
        self.custom_patterns = patterns;
        self
    }

    pub fn with_pull(mut self, pull: bool) -> Self {
        self.pull = pull;
        self
    }

    /// Scan the Docker image and return findings.
    pub async fn scan(&self) -> Result<Vec<Finding>> {
        use bollard::Docker;
        use futures_util::StreamExt;

        let docker = Docker::connect_with_local_defaults()
            .map_err(|e| anyhow::anyhow!("Cannot connect to Docker daemon: {}\nMake sure Docker is running.", e))?;

        // ── 1. Pull image (optional) ────────────────────────────────────────
        if self.pull {
            use bollard::image::CreateImageOptions;
            let (repo, tag) = parse_image_ref(&self.image);
            let opts = CreateImageOptions {
                from_image: repo.clone(),
                tag: tag.clone(),
                ..Default::default()
            };

            let mut stream = docker.create_image(Some(opts), None, None);
            while let Some(item) = stream.next().await {
                match item {
                    Ok(_) => {} // progress info, ignore
                    Err(e) => {
                        // If pull fails and image exists locally, continue anyway
                        scan_warn!("docker", "pull failed for {}: {} (trying local)", self.image, e);
                        break;
                    }
                }
            }
        }

        // ── 2. Create temporary container ───────────────────────────────────
        let container_config = bollard::container::Config {
            image: Some(self.image.clone()),
            // Override entrypoint so create doesn't need to validate CMD
            entrypoint: Some(vec!["/bin/true".to_string()]),
            ..Default::default()
        };

        let container = docker
            .create_container::<String, String>(None, container_config)
            .await
            .map_err(|e| {
                anyhow::anyhow!(
                    "Cannot create container from image {}: {}\nIs the image available locally or pullable?",
                    self.image,
                    e
                )
            })?;

        let container_id = container.id.clone();

        // ── 3. Export filesystem and scan ────────────────────────────────────
        let result = self
            .scan_container_export(&docker, &container_id)
            .await;

        // ── 4. Clean up container ───────────────────────────────────────────
        let _ = docker
            .remove_container(
                &container_id,
                Some(bollard::container::RemoveContainerOptions {
                    force: true,
                    ..Default::default()
                }),
            )
            .await;

        result
    }

    /// Export a container's filesystem as tar and scan each text file entry.
    async fn scan_container_export(
        &self,
        docker: &bollard::Docker,
        container_id: &str,
    ) -> Result<Vec<Finding>> {
        use futures_util::StreamExt;

        let detector = if self.custom_patterns.is_empty() {
            PatternDetector::new()
        } else {
            PatternDetector::with_custom_patterns(&self.custom_patterns)
        };

        // Collect the export stream into a single byte buffer.
        // Docker export produces a tar archive of the full filesystem.
        let mut tar_bytes: Vec<u8> = Vec::new();
        let mut stream = docker.export_container(container_id);
        while let Some(chunk) = stream.next().await {
            match chunk {
                Ok(bytes) => tar_bytes.extend_from_slice(&bytes),
                Err(e) => {
                    scan_warn!("docker", "error reading export stream: {}", e);
                    break;
                }
            }
        }

        let mut findings: Vec<Finding> = Vec::new();
        let mut archive = tar::Archive::new(tar_bytes.as_slice());

        for entry_result in archive.entries()? {
            let mut entry = match entry_result {
                Ok(e) => e,
                Err(e) => {
                    scan_warn!("docker", "tar entry error: {}", e);
                    continue;
                }
            };

            // Only process regular files
            if entry.header().entry_type() != tar::EntryType::Regular {
                continue;
            }

            let entry_path = match entry.path() {
                Ok(p) => p.to_path_buf(),
                Err(_) => continue,
            };

            let path_str = entry_path.to_string_lossy().to_string();

            // Skip known non-interesting system paths
            if SKIP_PREFIXES.iter().any(|pfx| path_str.starts_with(pfx)) {
                continue;
            }

            // Skip certificate stores and CA bundles (high false-positive sources)
            if SKIP_FILES.iter().any(|f| path_str == *f || path_str.starts_with(f)) {
                continue;
            }

            // Skip binary extensions
            if is_binary_path(&path_str) {
                continue;
            }

            // Skip large files
            let size = entry.header().size().unwrap_or(0) as usize;
            if size > MAX_FILE_SIZE || size == 0 {
                continue;
            }

            // Read content
            use std::io::Read;
            let mut content_bytes = Vec::with_capacity(size);
            if entry.read_to_end(&mut content_bytes).is_err() {
                continue;
            }

            // Skip binary content (null bytes)
            if content_bytes[..content_bytes.len().min(512)].contains(&0u8) {
                continue;
            }

            let content = match String::from_utf8(content_bytes) {
                Ok(s) => s,
                Err(_) => continue,
            };

            // Build virtual path: docker://image/path/inside/container
            let virtual_path = PathBuf::from(format!("docker://{}/{}", self.image, path_str));

            match self.scan_text_content(&content, &virtual_path, &detector) {
                Ok(file_findings) => findings.extend(file_findings),
                Err(e) => {
                    scan_warn!("docker", "scan error for {}: {}", path_str, e);
                }
            }
        }

        Ok(findings)
    }

    /// Core text scanning logic.
    fn scan_text_content(
        &self,
        content: &str,
        virtual_path: &std::path::Path,
        detector: &PatternDetector,
    ) -> Result<Vec<Finding>> {
        let mut findings = Vec::new();
        let file_context = ContextAnalyzer::analyze_file(virtual_path);
        let lines: Vec<&str> = content.lines().collect();

        for (line_num, line) in lines.iter().enumerate() {
            if ContextAnalyzer::is_placeholder(line) || line.len() > 5000 {
                continue;
            }

            let is_comment = ContextAnalyzer::is_comment(line);
            let pattern_matches =
                detector.scan_line_with_positions(line, self.entropy_threshold);

            for pm in pattern_matches {
                let mut secret = pm.secret;
                if is_comment {
                    secret.confidence *= 0.75;
                }

                let line_before = if line_num > 0 {
                    Some(lines[line_num - 1].to_string())
                } else {
                    None
                };
                let line_after = if line_num + 1 < lines.len() {
                    Some(lines[line_num + 1].to_string())
                } else {
                    None
                };

                secret.severity = ContextAnalyzer::adjust_severity(
                    secret.severity,
                    &Context {
                        line_before: line_before.clone(),
                        line_content: line.to_string(),
                        line_after: line_after.clone(),
                        is_test_file: file_context.is_test_file,
                        is_config_file: file_context.is_config_file,
                        is_documentation: file_context.is_documentation,
                        file_extension: file_context.file_extension.clone(),
                    },
                );

                let location = Location {
                    file_path: virtual_path.to_path_buf(),
                    line_number: line_num + 1,
                    column_start: pm.column_start,
                    column_end: pm.column_end,
                    commit_hash: None,
                    commit_author: None,
                    commit_date: None,
                };

                let context = ContextAnalyzer::build_context(
                    line.to_string(),
                    line_before,
                    line_after,
                    &file_context,
                );

                findings.push(Finding::new(secret, location, context));
            }
        }

        Ok(findings)
    }
}

/// Parse `image:tag` into (image, tag). Defaults tag to "latest".
fn parse_image_ref(image: &str) -> (String, String) {
    // Handle images with digests (image@sha256:...)
    if image.contains('@') {
        return (image.to_string(), String::new());
    }

    // Handle images with registry port (registry:5000/image:tag)
    // Split on the last colon that's not part of a port number
    if let Some(colon_pos) = image.rfind(':') {
        let after = &image[colon_pos + 1..];
        // If the part after : contains a /, it's a registry port, not a tag
        if !after.contains('/') {
            return (
                image[..colon_pos].to_string(),
                after.to_string(),
            );
        }
    }

    (image.to_string(), "latest".to_string())
}

fn is_binary_path(path: &str) -> bool {
    if let Some(dot_pos) = path.rfind('.') {
        let ext = &path[dot_pos + 1..];
        BINARY_EXTENSIONS.contains(&ext.to_lowercase().as_str())
    } else {
        false
    }
}

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

    #[test]
    fn test_parse_image_ref_simple() {
        let (repo, tag) = parse_image_ref("nginx:1.25");
        assert_eq!(repo, "nginx");
        assert_eq!(tag, "1.25");
    }

    #[test]
    fn test_parse_image_ref_latest() {
        let (repo, tag) = parse_image_ref("nginx");
        assert_eq!(repo, "nginx");
        assert_eq!(tag, "latest");
    }

    #[test]
    fn test_parse_image_ref_registry() {
        let (repo, tag) = parse_image_ref("ghcr.io/org/app:v2");
        assert_eq!(repo, "ghcr.io/org/app");
        assert_eq!(tag, "v2");
    }

    #[test]
    fn test_parse_image_ref_registry_port() {
        let (repo, tag) = parse_image_ref("registry:5000/myapp:latest");
        assert_eq!(repo, "registry:5000/myapp");
        assert_eq!(tag, "latest");
    }

    #[test]
    fn test_binary_path_detection() {
        assert!(is_binary_path("usr/bin/app.exe"));
        assert!(is_binary_path("opt/data/image.png"));
        assert!(!is_binary_path("etc/nginx/nginx.conf"));
        assert!(!is_binary_path("app/config.yaml"));
    }
}