ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
//! Sandbox Detection Module
//!
//! Detects if the application is running in a sandboxed or virtualized environment.
//! This is important for ethical data collection - we should never collect or transmit
//! data when running in analysis/testing environments.
//!
//! # Detection Methods
//!
//! - Virtual machine detection (VMware, VirtualBox, QEMU, Hyper-V, KVM)
//! - Container detection (Docker, LXC, systemd-nspawn)
//! - Windows Sandbox detection
//! - macOS sandbox detection
//! - Debugger detection
//! - Known analysis tool paths
//!
//! # Example
//!
//! ```no_run
//! use ironmonitor::sandbox::SandboxDetector;
//!
//! let detector = SandboxDetector::new();
//! if detector.is_sandboxed() {
//!     println!("Running in sandbox - no data collection");
//!     return;
//! }
//! ```

#[cfg(target_os = "linux")]
use std::fs;
#[cfg(any(target_os = "linux", windows))]
use std::path::Path;

/// Sandbox detection results
#[derive(Debug, Clone, Default)]
pub struct SandboxInfo {
    /// Is running in a virtual machine
    pub is_vm: bool,

    /// Is running in a container
    pub is_container: bool,

    /// Is running under Windows Sandbox
    pub is_windows_sandbox: bool,

    /// Is running under macOS sandbox
    pub is_macos_sandbox: bool,

    /// Is running under Wine/compatibility layer.
    ///
    /// Never set. Wine and Proton are not sandboxes, and their environment
    /// variables are not evidence of one. The field stays so the public struct
    /// does not change.
    pub is_wine: bool,

    /// Is being debugged
    pub is_debugged: bool,

    /// Detected environment name
    pub environment: Option<String>,

    /// All detected indicators
    pub indicators: Vec<String>,
}

impl SandboxInfo {
    /// Check if any sandbox indicators are present
    pub fn is_sandboxed(&self) -> bool {
        self.is_vm
            || self.is_container
            || self.is_windows_sandbox
            || self.is_macos_sandbox
            || self.is_wine
            || self.is_debugged
    }

    /// Get a human-readable summary
    pub fn summary(&self) -> String {
        if !self.is_sandboxed() {
            return "Not sandboxed".to_string();
        }

        let mut parts = Vec::new();
        if self.is_vm {
            parts.push("Virtual Machine");
        }
        if self.is_container {
            parts.push("Container");
        }
        if self.is_windows_sandbox {
            parts.push("Windows Sandbox");
        }
        if self.is_macos_sandbox {
            parts.push("macOS Sandbox");
        }
        if self.is_wine {
            parts.push("Wine/Compatibility Layer");
        }
        if self.is_debugged {
            parts.push("Debugger Attached");
        }

        if let Some(env) = &self.environment {
            format!("Sandboxed: {} ({})", parts.join(", "), env)
        } else {
            format!("Sandboxed: {}", parts.join(", "))
        }
    }
}

/// Sandbox detector
pub struct SandboxDetector;

impl SandboxDetector {
    /// Create a new sandbox detector
    pub fn new() -> Self {
        Self
    }

    /// Perform comprehensive sandbox detection
    pub fn detect(&self) -> SandboxInfo {
        let mut info = SandboxInfo::default();

        // VM detection
        self.detect_vm(&mut info);

        // Container detection
        self.detect_container(&mut info);

        // Windows Sandbox detection
        #[cfg(windows)]
        self.detect_windows_sandbox(&mut info);

        // macOS sandbox detection
        #[cfg(target_os = "macos")]
        self.detect_macos_sandbox(&mut info);

        // Debugger detection
        self.detect_debugger(&mut info);

        info
    }

    /// Quick check if sandboxed (convenience method)
    pub fn is_sandboxed(&self) -> bool {
        self.detect().is_sandboxed()
    }

    /// Detect virtual machine environments
    fn detect_vm(&self, info: &mut SandboxInfo) {
        // Linux: Check /sys/class/dmi/id/product_name and other DMI files
        #[cfg(target_os = "linux")]
        {
            let vm_indicators = [
                (
                    "/sys/class/dmi/id/product_name",
                    vec!["VirtualBox", "VMware", "QEMU", "KVM", "Bochs"],
                ),
                // "Microsoft Corporation" is deliberately absent: it is the
                // sys_vendor of every Surface, which is bare metal. A Hyper-V
                // guest is caught by the hypervisor CPU flag below.
                (
                    "/sys/class/dmi/id/sys_vendor",
                    vec!["QEMU", "VMware", "VirtualBox"],
                ),
                (
                    "/sys/class/dmi/id/board_vendor",
                    vec!["VMware", "VirtualBox"],
                ),
                ("/sys/class/dmi/id/bios_vendor", vec!["SeaBIOS", "Bochs"]),
            ];

            for (path, indicators) in &vm_indicators {
                if let Ok(content) = fs::read_to_string(path) {
                    for indicator in indicators {
                        if content.contains(indicator) {
                            info.is_vm = true;
                            info.environment = Some(indicator.to_string());
                            info.indicators
                                .push(format!("{} detected in {}", indicator, path));
                        }
                    }
                }
            }

            // Check for hypervisor CPU flag
            if let Ok(cpuinfo) = fs::read_to_string("/proc/cpuinfo") {
                if cpuinfo.contains("hypervisor") {
                    info.is_vm = true;
                    info.indicators
                        .push("Hypervisor CPU flag detected".to_string());
                }
            }

            // Check for VM-specific devices
            if Path::new("/dev/vboxguest").exists() {
                info.is_vm = true;
                info.environment = Some("VirtualBox".to_string());
                info.indicators
                    .push("VirtualBox guest device found".to_string());
            }

            if Path::new("/dev/vmci").exists() {
                info.is_vm = true;
                info.environment = Some("VMware".to_string());
                info.indicators.push("VMware device found".to_string());
            }
        }

        // Windows: Check registry and WMI (would require winreg crate)
        #[cfg(windows)]
        {
            // This read `C:\Windows\System32\drivers\vmbus.sys` and set
            // `is_vm` if the contents were non-empty. It was wrong twice over:
            // the file ships with every modern Windows install, host or guest,
            // so its presence proves nothing; and it is a binary driver, so
            // `read_to_string` fails on invalid UTF-8 and the check never ran
            // at all. Both confirmed on a bare-metal Windows 11 desktop, where
            // the file is present, 210 KB, and invalid UTF-8 at byte 2.
            //
            // 3.10.0 already built the correct check in `virtualization::detect`:
            // it reads the hypervisor bit and vendor string out of CPUID and
            // distinguishes a Hyper-V root partition from a guest via leaf
            // 0x40000003. Use it rather than keep a second, worse one.
            if crate::virtualization::detect::detect_platform()
                == crate::virtualization::detect::VirtPlatform::VirtualMachine
            {
                info.is_vm = true;
                let named = crate::virtualization::detect::detect_hypervisor()
                    .map(|h| format!("{:?}", h.hypervisor));
                info.environment = named.clone();
                info.indicators.push(match named {
                    Some(name) => format!("{name} reported by CPUID"),
                    None => "hypervisor reported by CPUID".to_string(),
                });
            }
        }

        // macOS: Check for virtualization
        #[cfg(target_os = "macos")]
        {
            if let Ok(output) = std::process::Command::new("sysctl")
                .arg("-n")
                .arg("machdep.cpu.features")
                .output()
            {
                let features = String::from_utf8_lossy(&output.stdout);
                if features.contains("VMM") || features.contains("Hypervisor") {
                    info.is_vm = true;
                    info.indicators
                        .push("Hypervisor features detected".to_string());
                }
            }
        }
    }

    /// Detect container environments
    fn detect_container(&self, _info: &mut SandboxInfo) {
        #[cfg(target_os = "linux")]
        {
            // Check for Docker
            if Path::new("/.dockerenv").exists() {
                _info.is_container = true;
                _info.environment = Some("Docker".to_string());
                _info
                    .indicators
                    .push("Docker environment file found".to_string());
            }

            // Check cgroup for container indicators
            if let Ok(cgroup) = fs::read_to_string("/proc/1/cgroup") {
                if cgroup.contains("docker")
                    || cgroup.contains("lxc")
                    || cgroup.contains("kubepods")
                {
                    _info.is_container = true;
                    if cgroup.contains("docker") {
                        _info.environment = Some("Docker".to_string());
                    } else if cgroup.contains("lxc") {
                        _info.environment = Some("LXC".to_string());
                    } else if cgroup.contains("kubepods") {
                        _info.environment = Some("Kubernetes".to_string());
                    }
                    _info
                        .indicators
                        .push("Container cgroup detected".to_string());
                }
            }

            // Check for systemd-nspawn
            if let Ok(env) = std::env::var("container") {
                _info.is_container = true;
                _info.environment = Some(env.clone());
                _info.indicators.push(format!("Container env var: {}", env));
            }

            // Check for Flatpak
            if Path::new("/.flatpak-info").exists() {
                _info.is_container = true;
                _info.environment = Some("Flatpak".to_string());
                _info
                    .indicators
                    .push("Flatpak sandbox detected".to_string());
            }

            // Check for Snap
            if std::env::var("SNAP").is_ok() {
                _info.is_container = true;
                _info.environment = Some("Snap".to_string());
                _info.indicators.push("Snap sandbox detected".to_string());
            }
        }
    }

    /// Detect Windows Sandbox
    #[cfg(windows)]
    fn detect_windows_sandbox(&self, info: &mut SandboxInfo) {
        // A `SANDBOX-` computer name used to set `is_windows_sandbox`. Any user
        // can name a machine that way, so the name is not evidence that this
        // process runs in Windows Sandbox.

        // Check for Windows Sandbox specific marker file (more reliable than Containers directory)
        // The Containers directory exists on all modern Windows systems, not just sandbox
        if Path::new("C:\\Windows\\System32\\uxtheme.dll").exists() {
            // Check for Windows Sandbox-specific indicator: Sandbox always has limited user profile
            if let Ok(user_profile) = std::env::var("USERPROFILE") {
                // Windows Sandbox typically uses WDAGUtilityAccount or similar transient accounts
                if user_profile.contains("WDAGUtilityAccount")
                    || user_profile.contains("ContainerUser")
                {
                    info.is_windows_sandbox = true;
                    info.indicators
                        .push("Windows Sandbox user profile detected".to_string());
                }
            }
        }

        // Check for AppContainer/AppJail (UWP apps)
        if std::env::var("LOCALAPPDATA")
            .map(|p| p.contains("Packages"))
            .unwrap_or(false)
        {
            // Only mark as sandboxed if we're actually running as a packaged app
            // Check for package identity
            if std::env::var("PACKAGE_FAMILY_NAME").is_ok() {
                info.is_windows_sandbox = true;
                info.indicators.push("AppContainer detected".to_string());
            }
        }
    }

    /// Detect macOS sandbox
    #[cfg(target_os = "macos")]
    fn detect_macos_sandbox(&self, info: &mut SandboxInfo) {
        // Check if running in macOS sandbox
        if std::env::var("APP_SANDBOX_CONTAINER_ID").is_ok() {
            info.is_macos_sandbox = true;
            info.environment = Some("macOS Sandbox".to_string());
            info.indicators
                .push("macOS sandbox container ID found".to_string());
        }

        // `sandbox-exec -p "(version 1)" true` used to set `is_macos_sandbox`.
        // It succeeds on every Mac, because the tool ships with the OS, so it
        // reported a sandbox on machines that are not in one. Only the
        // container identity above says the process is sandboxed.
    }

    // Wine and Proton detection was removed. `WINE`, `WINEPREFIX` and
    // `STEAM_COMPAT_DATA_PATH` used to set `is_wine`, which made
    // `is_sandboxed()` true, and `ConsentManager` then refused every scope for
    // Proton users. Those variables describe a compatibility layer, not a
    // sandbox. A `~/.wine` directory was dropped for the same kind of reason:
    // any Wine install leaves it behind, whether or not Wine is running.

    /// Detect debugger attachment
    // Only Linux and Windows look for a debugger, so `info` is unused elsewhere.
    #[cfg_attr(not(any(target_os = "linux", windows)), allow(unused_variables))]
    fn detect_debugger(&self, info: &mut SandboxInfo) {
        #[cfg(target_os = "linux")]
        {
            // Check /proc/self/status for TracerPid
            if let Ok(status) = fs::read_to_string("/proc/self/status") {
                for line in status.lines() {
                    if line.starts_with("TracerPid:") {
                        if let Some(pid_str) = line.split_whitespace().nth(1) {
                            if let Ok(pid) = pid_str.parse::<i32>() {
                                if pid != 0 {
                                    info.is_debugged = true;
                                    info.indicators
                                        .push(format!("Debugger attached (PID: {})", pid));
                                }
                            }
                        }
                    }
                }
            }
        }

        #[cfg(windows)]
        {
            // Check if debugger is present using Windows API
            use windows::Win32::System::Diagnostics::Debug::IsDebuggerPresent;
            unsafe {
                if IsDebuggerPresent().as_bool() {
                    info.is_debugged = true;
                    info.indicators
                        .push("Debugger detected via IsDebuggerPresent".to_string());
                }
            }
        }

        // There is deliberately no environment-variable heuristic here.
        //
        // The list used to be `["_", "LLDB_DEBUGSERVER_PATH", "GDB",
        // "PYTHONBREAKPOINT"]`, and `_` is not a debugger variable at all:
        // every POSIX shell sets it to the last argument of the previous
        // command, so every run launched from bash, zsh or sh reported
        // "Sandboxed: Debugger Attached". On this desktop that made
        // `is_sandboxed()` true, which made `has_consent` false for every
        // scope, which made `ironmon privacy status` answer "DENIED" on the line
        // after `ironmon privacy opt-in` said "enabled". The other three say
        // nothing about *this* process either: gdb does not export `GDB`, and
        // `PYTHONBREAKPOINT` configures a Python hook, in a Rust binary.
        //
        // The two checks above are the real ones. macOS has none, and the
        // honest answer there is `false` with nothing claimed, rather than a
        // guess that fires on a shell variable.
    }
}

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

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

    /// `$_` is set by every POSIX shell to the last argument of the previous
    /// command. It was in this module's debugger-variable list, so any run
    /// started from bash, zsh or sh reported a debugger and therefore a
    /// sandbox — and `ConsentManager::has_consent` refuses every scope inside
    /// a sandbox, so `ironmon privacy status` answered "DENIED" immediately
    /// after `ironmon privacy opt-in` recorded consent.
    ///
    /// The test runner sets `_` under `cargo test` from a shell, so this
    /// assertion exercised the defect directly: it failed before the list was
    /// removed. A real debugger attached to the test process would also fail
    /// it, which is the correct behaviour and not a flake.
    #[test]
    fn a_shell_variable_is_not_a_debugger() {
        let info = SandboxDetector::new().detect();

        assert!(
            !info.is_debugged,
            "reported a debugger with none attached; indicators: {:?}",
            info.indicators
        );

        for indicator in &info.indicators {
            assert!(
                !indicator.contains("env var"),
                concat!(
                    "an environment variable is being used as evidence of a ",
                    "sandbox: {}"
                ),
                indicator
            );
        }
    }

    /// A Proton (Steam compatibility layer) process sets `STEAM_COMPAT_DATA_PATH`
    /// and usually `WINEPREFIX`. Neither is a sandbox, so neither may make
    /// `is_sandboxed()` true, which `ConsentManager` treats as a refusal to
    /// collect anything. A machine named `SANDBOX-*` is not a sandbox either.
    /// The assertions look only at evidence from these variables, so they hold
    /// on any host.
    #[test]
    fn a_proton_environment_is_not_reported_as_sandboxed() {
        let vars = [
            "STEAM_COMPAT_DATA_PATH",
            "WINEPREFIX",
            "WINE",
            "COMPUTERNAME",
        ];
        std::env::set_var("STEAM_COMPAT_DATA_PATH", "/tmp/compatdata/1091500");
        std::env::set_var("WINEPREFIX", "/tmp/compatdata/1091500/pfx");
        std::env::set_var("WINE", "/usr/bin/wine");
        std::env::set_var("COMPUTERNAME", "SANDBOX-PROTON");

        let info = SandboxDetector::new().detect();

        for var in vars {
            // Only the test's own variables are removed; the value a real
            // host set before the test ran is not restored.
            std::env::remove_var(var);
        }

        assert!(!info.is_wine, "Proton/Wine variables set is_wine");
        assert_ne!(info.environment.as_deref(), Some("Proton"));
        assert_ne!(info.environment.as_deref(), Some("Wine"));
        for indicator in &info.indicators {
            assert!(
                !indicator.contains("Proton") && !indicator.contains("Wine"),
                "a compatibility layer is reported as a sandbox: {}",
                indicator
            );
            assert!(
                !indicator.contains("computer name"),
                "a computer name is reported as a sandbox: {}",
                indicator
            );
        }
    }

    #[test]
    fn test_sandbox_detector_creation() {
        let detector = SandboxDetector::new();
        let info = detector.detect();

        // Test should work regardless of environment
        assert!(!info.summary().is_empty());
    }

    #[test]
    fn test_sandbox_info_not_sandboxed() {
        let info = SandboxInfo::default();
        assert!(!info.is_sandboxed());
        assert_eq!(info.summary(), "Not sandboxed");
    }

    #[test]
    fn test_sandbox_info_vm() {
        let info = SandboxInfo {
            is_vm: true,
            environment: Some("VirtualBox".to_string()),
            ..Default::default()
        };

        assert!(info.is_sandboxed());
        assert!(info.summary().contains("Virtual Machine"));
    }
}