host-identity 1.0.0

Stable, collision-resistant host identity resolution across platforms, container runtimes, cloud providers, and Kubernetes
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
//! Linux identity sources: `/etc/machine-id`, D-Bus machine-id, SMBIOS/DMI.
//!
//! # Identity scope
//!
//! These sources live at two distinct scopes:
//!
//! - `MachineIdFile` and `DbusMachineIdFile` are **per-host-OS**:
//!   written once when the OS is provisioned and tied to the install.
//! - `DmiProductUuid` is **per-instance**: the SMBIOS system UUID is
//!   assigned by the hypervisor (on VMs) or the OEM (on bare metal)
//!   and identifies the hardware/VM, not the OS install.
//!
//! In container deployments the distinction collapses: none of these
//! namespaces are container-isolated, so a process inside a container
//! reads the same value every sibling container on that host reads.
//! `/sys/devices/virtual/dmi/id/product_uuid` isn't namespaced at all
//! — the container sees the underlying VM's SMBIOS UUID directly.
//! Red Hat container images go further and bind-mount the host's
//! `/etc/machine-id` into the container, so even the "file" path
//! leaks host identity into the container. See Docker community
//! discussion of [host `machine-id` visibility in containers](https://forums.docker.com/t/host-machine-id-visible-from-containers/100533)
//! and the sysbox issue [open sys/devices/virtual/dmi/id/product_uuid](https://github.com/nestybox/sysbox/issues/405)
//! for the non-namespaced sysfs path.
//!
//! `ContainerId` (and, in pods, `KubernetesPodUid`) must sit above
//! these sources in any chain that wants per-container identity; the
//! default chains do this for you. See `docs/algorithm.md` →
//! "Identity scope" for the full discussion.
//!
//! Authoritative references:
//!
//! - [`machine-id(5)`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html)
//!   — systemd-managed per-host identifier, initialised once on first boot.
//!   The `uninitialized` sentinel is specified there as the marker for the
//!   early-boot window before the ID has been written.
//! - [D-Bus specification, UUIDs](https://dbus.freedesktop.org/doc/dbus-specification.html#uuids)
//!   — defines `/var/lib/dbus/machine-id` as the interoperable machine UUID.
//!   On systemd systems this is a symlink to `/etc/machine-id`.
//! - [`sysfs-class-dmi(5)` / kernel sysfs-firmware-dmi-tables](https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-firmware-dmi-tables)
//!   and the SMBIOS specification from the
//!   [DMTF](https://www.dmtf.org/dsp/DSP0134) — `/sys/class/dmi/id/product_uuid`
//!   exposes the SMBIOS system UUID (type 1 "UUID" field). Readable by root
//!   only on most distributions; this crate swallows `PermissionDenied` to
//!   let unprivileged callers fall through to other sources.

use std::path::{Path, PathBuf};

use crate::error::Error;
use crate::source::{Probe, Source, SourceKind};
use crate::sources::util::{NormalizeOutcome, classify, read_capped};

macro_rules! file_source {
    ($name:ident, $kind:expr, $default:expr, $doc:literal) => {
        #[doc = $doc]
        #[derive(Debug, Clone)]
        pub struct $name {
            path: PathBuf,
        }

        impl $name {
            #[doc = concat!("Read from the standard path (`", $default, "`).")]
            #[must_use]
            pub fn new() -> Self {
                Self {
                    path: PathBuf::from($default),
                }
            }

            /// Read from a caller-supplied path. Useful for tests and unusual
            /// image layouts.
            #[must_use]
            pub fn at(path: impl Into<PathBuf>) -> Self {
                Self { path: path.into() }
            }

            /// The configured path.
            #[must_use]
            pub fn path(&self) -> &Path {
                &self.path
            }
        }

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

        impl Source for $name {
            fn kind(&self) -> SourceKind {
                $kind
            }
            fn probe(&self) -> Result<Option<Probe>, Error> {
                read_id_file($kind, &self.path)
            }
        }
    };
}

file_source!(
    MachineIdFile,
    SourceKind::MachineId,
    "/etc/machine-id",
    "`/etc/machine-id` — the systemd-managed primary host identifier on modern Linux."
);

file_source!(
    DbusMachineIdFile,
    SourceKind::DbusMachineId,
    "/var/lib/dbus/machine-id",
    "`/var/lib/dbus/machine-id` — D-Bus machine ID. Often a symlink to `/etc/machine-id` \
     but present on its own on some minimal images."
);

/// `/sys/class/dmi/id/product_uuid` — SMBIOS system UUID. Distinct per
/// physical or virtual hardware, so it distinguishes cloned VMs that share
/// a machine-id, but requires root on most distributions.
///
/// # Vendor-placeholder filtering
///
/// SMBIOS commonly ships vendor-default values that are stable *per model*,
/// not per machine. Returning one of those would produce a silently
/// non-unique identity shared by every box with the same mainboard. This
/// source additionally rejects, by returning `Ok(None)` with a
/// `log::debug!` entry:
///
/// - `00000000-0000-0000-0000-000000000000` (all-zero)
/// - `ffffffff-ffff-ffff-ffff-ffffffffffff` (all-F, case-insensitive)
/// - Any UUID whose 32 hex nibbles are all the same character
///   (`11111111-…`, `aaaaaaaa-…`, etc.)
/// - A conservative curated list of well-known vendor placeholders
///   (e.g. `03000200-0400-0500-0006-000700080009`), sourced from
///   [fwupd](https://github.com/fwupd/fwupd) and `dmidecode`.
///
/// Anything not matching the filter passes through unchanged — the intent
/// is to reject *known* garbage, not to gate on UUID shape.
#[derive(Debug, Clone)]
pub struct DmiProductUuid {
    path: PathBuf,
}

impl DmiProductUuid {
    /// Read from the standard path (`/sys/class/dmi/id/product_uuid`).
    #[must_use]
    pub fn new() -> Self {
        Self {
            path: PathBuf::from("/sys/class/dmi/id/product_uuid"),
        }
    }

    /// Read from a caller-supplied path. Useful for tests and unusual
    /// image layouts.
    #[must_use]
    pub fn at(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    /// The configured path.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }
}

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

impl Source for DmiProductUuid {
    fn kind(&self) -> SourceKind {
        SourceKind::Dmi
    }
    fn probe(&self) -> Result<Option<Probe>, Error> {
        read_dmi_file(&self.path)
    }
}

/// Well-known vendor-placeholder UUIDs, stored lowercase. Sourced from
/// fwupd's UEFI plugin quirks list and `dmidecode` field notes. Kept
/// deliberately conservative — a missing entry means the value passes
/// through, which is the less-bad failure mode.
const DMI_PLACEHOLDER_UUIDS: &[&str] = &[
    // Supermicro / AMI golden default seen on a wide range of boards.
    "03000200-0400-0500-0006-000700080009",
];

/// Return `true` if `value` looks like SMBIOS vendor-default garbage that
/// should be rejected rather than used as an identity.
fn is_dmi_garbage(value: &str) -> bool {
    let lower = value.to_ascii_lowercase();
    if DMI_PLACEHOLDER_UUIDS.iter().any(|p| *p == lower) {
        return true;
    }
    is_all_same_nibble_uuid(&lower)
}

/// Return `true` if the input is a canonical 8-4-4-4-12 hyphenated UUID
/// whose 32 hex nibbles are all the same character. Subsumes the
/// all-zero and all-F cases and rejects `11111111-…`, `aaaaaaaa-…`, etc.
///
/// The 32-hex-digit gate keeps short non-UUID values like `"abc"` from
/// false-positively hitting this rule.
fn is_all_same_nibble_uuid(value: &str) -> bool {
    let mut chars = value.chars().filter(|c| *c != '-');
    let Some(first) = chars.next() else {
        return false;
    };
    if !first.is_ascii_hexdigit() {
        return false;
    }
    let mut count = 1usize;
    for c in chars {
        if c != first {
            return false;
        }
        count += 1;
    }
    count == 32
}

fn read_dmi_file(path: &Path) -> Result<Option<Probe>, Error> {
    match read_id_file(SourceKind::Dmi, path)? {
        Some(probe) if is_dmi_garbage(probe.value()) => {
            log::debug!(
                "host-identity: DMI product_uuid {} matches a known vendor-placeholder; \
                 falling through",
                probe.value()
            );
            Ok(None)
        }
        other => Ok(other),
    }
}

fn read_id_file(kind: SourceKind, path: &Path) -> Result<Option<Probe>, Error> {
    match read_capped(path) {
        Ok(content) => match classify(&content) {
            NormalizeOutcome::Usable(value) => Ok(Some(Probe::new(kind, value))),
            NormalizeOutcome::Sentinel => Err(Error::Uninitialized {
                source_kind: kind,
                path: PathBuf::from(path),
            }),
            NormalizeOutcome::Empty => Ok(None),
        },
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => {
            log::debug!(
                "host-identity: permission denied reading {}",
                path.display()
            );
            Ok(None)
        }
        Err(source) => Err(Error::Io {
            source_kind: kind,
            path: PathBuf::from(path),
            source,
        }),
    }
}

/// Heuristic container-runtime detection.
///
/// Mirrors the checks agent-go uses: `/.dockerenv` existence, runtime markers
/// in `/proc/1/cgroup`. Used by [`crate::HostId::in_container`] for
/// provenance; does not affect which source is chosen (that is the resolver's
/// job — add or remove [`crate::sources::ContainerId`] to change behaviour).
#[must_use]
pub(crate) fn in_container() -> bool {
    const MARKERS: &[&str] = &["docker", "kubepods", "containerd", "podman", "lxc", "crio"];
    Path::new("/.dockerenv").exists()
        || std::fs::read_to_string("/proc/1/cgroup").is_ok_and(|cgroup| {
            cgroup
                .split(['/', ':', '-', '.', '_', '\n'])
                .any(|seg| MARKERS.contains(&seg))
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::{NamedTempFile, TempDir};

    #[test]
    fn machine_id_file_rejects_uninitialized_sentinel() {
        let mut f = NamedTempFile::new().unwrap();
        writeln!(f, "uninitialized").unwrap();
        let err = read_id_file(SourceKind::MachineId, f.path()).expect_err("sentinel must error");
        match err {
            Error::Uninitialized { path, source_kind } => {
                assert_eq!(path, f.path());
                assert_eq!(source_kind, SourceKind::MachineId);
            }
            other => panic!("expected Uninitialized, got {other:?}"),
        }
    }

    #[test]
    fn machine_id_file_accepts_normal_value() {
        let mut f = NamedTempFile::new().unwrap();
        writeln!(f, "abc123").unwrap();
        let probe = read_id_file(SourceKind::MachineId, f.path())
            .unwrap()
            .unwrap();
        assert_eq!(probe.value(), "abc123");
    }

    #[test]
    fn machine_id_file_missing_is_none() {
        let dir = TempDir::new().unwrap();
        let missing = dir.path().join("definitely-not-there");
        let probe = read_id_file(SourceKind::MachineId, &missing).unwrap();
        assert!(probe.is_none());
    }

    #[test]
    fn machine_id_file_empty_is_none() {
        let f = NamedTempFile::new().unwrap();
        let probe = read_id_file(SourceKind::MachineId, f.path()).unwrap();
        assert!(probe.is_none());
    }

    #[test]
    fn machine_id_file_whitespace_only_is_none() {
        let mut f = NamedTempFile::new().unwrap();
        write!(f, "   \n\t ").unwrap();
        let probe = read_id_file(SourceKind::MachineId, f.path()).unwrap();
        assert!(probe.is_none());
    }

    #[test]
    fn machine_id_file_reports_io_error_for_directory() {
        // read_to_string on a directory hits the generic IO arm and must
        // surface as Error::Io carrying the path.
        let dir = TempDir::new().unwrap();
        let err = read_id_file(SourceKind::MachineId, dir.path())
            .expect_err("reading a directory must error");
        match err {
            Error::Io { path, .. } => assert_eq!(path, dir.path()),
            other => panic!("expected Io, got {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn machine_id_file_permission_denied_is_none() {
        use std::os::unix::fs::PermissionsExt;
        use std::path::{Path, PathBuf};

        /// Restores the file's readable permissions on drop so a panic
        /// mid-test can't leave the tempfile unreadable (which would
        /// break tempfile cleanup).
        struct PermGuard(PathBuf);
        impl Drop for PermGuard {
            fn drop(&mut self) {
                let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o600));
            }
        }

        // Skip when running as root — chmod 0o000 doesn't deny root.
        if nix_is_root() {
            return;
        }

        let mut f = NamedTempFile::new().unwrap();
        writeln!(f, "abc123").unwrap();
        let path: &Path = f.path();
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o000)).unwrap();
        let _guard = PermGuard(path.to_path_buf());

        let probe = read_id_file(SourceKind::MachineId, path)
            .expect("permission denied should be swallowed to Ok(None)");
        assert!(probe.is_none());
    }

    fn dmi_tempfile(body: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        write!(f, "{body}").unwrap();
        f
    }

    fn dmi_probe(body: &str) -> Option<Probe> {
        let f = dmi_tempfile(body);
        read_dmi_file(f.path()).unwrap()
    }

    #[test]
    fn dmi_rejects_all_zero_uuid() {
        assert!(dmi_probe("00000000-0000-0000-0000-000000000000\n").is_none());
    }

    #[test]
    fn dmi_rejects_all_f_uuid_lower() {
        assert!(dmi_probe("ffffffff-ffff-ffff-ffff-ffffffffffff\n").is_none());
    }

    #[test]
    fn dmi_rejects_all_f_uuid_upper() {
        assert!(dmi_probe("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF\n").is_none());
    }

    #[test]
    fn dmi_rejects_all_same_nibble_1() {
        assert!(dmi_probe("11111111-1111-1111-1111-111111111111\n").is_none());
    }

    #[test]
    fn dmi_rejects_all_same_nibble_a() {
        assert!(dmi_probe("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa\n").is_none());
    }

    #[test]
    fn dmi_rejects_supermicro_ami_placeholder() {
        // Removing this entry from DMI_PLACEHOLDER_UUIDS must fail this
        // test — deliberate regression coverage.
        assert!(dmi_probe("03000200-0400-0500-0006-000700080009\n").is_none());
    }

    #[test]
    fn dmi_rejects_supermicro_ami_placeholder_uppercase() {
        assert!(
            dmi_probe(
                "03000200-0400-0500-0006-000700080009"
                    .to_ascii_uppercase()
                    .as_str()
            )
            .is_none()
        );
    }

    #[test]
    fn dmi_rejects_garbage_with_trailing_whitespace() {
        // Confirms the filter composes with classify's trim.
        assert!(dmi_probe("  00000000-0000-0000-0000-000000000000  \n\t").is_none());
    }

    #[test]
    fn dmi_accepts_plausible_real_uuid() {
        let probe = dmi_probe("4c4c4544-0039-5710-8052-b4c04f384833\n").unwrap();
        assert_eq!(probe.value(), "4c4c4544-0039-5710-8052-b4c04f384833");
    }

    #[test]
    fn dmi_accepts_non_uuid_shape() {
        // The 32-hex-digit gate in is_all_same_nibble_uuid must not
        // false-positively reject short non-UUID values.
        let probe = dmi_probe("abcdef\n").unwrap();
        assert_eq!(probe.value(), "abcdef");
    }

    #[test]
    fn machine_id_file_accepts_all_zero_uuid() {
        // Negative control: the DMI-specific garbage filter must not
        // leak into MachineIdFile. Opaque per-host strings are not
        // subject to SMBIOS placeholder rules.
        let f = dmi_tempfile("00000000-0000-0000-0000-000000000000\n");
        let probe = read_id_file(SourceKind::MachineId, f.path())
            .unwrap()
            .unwrap();
        assert_eq!(probe.value(), "00000000-0000-0000-0000-000000000000");
    }

    #[cfg(unix)]
    fn nix_is_root() -> bool {
        // Avoid pulling in a new dep — read `id -u` via libc would also work,
        // but checking the effective UID via /proc/self/status is trivial.
        std::fs::read_to_string("/proc/self/status")
            .ok()
            .and_then(|s| {
                s.lines()
                    .find_map(|l| l.strip_prefix("Uid:"))
                    .and_then(|l| l.split_whitespace().next().map(str::to_owned))
            })
            .is_some_and(|uid| uid == "0")
    }
}